Posts Tagged ‘ Matlab

Simple beam pattern in Python

It’s been a long time since I’ve

(a) used Python, numpy, scipy, or matplotlib

(b) done a beam pattern calculation of any kind

So I thought it would be a good chance to brush up on several things all at once, and maybe even have the satisfaction of making a pretty picture at the end of the night.

Well, here’s the (perhaps not so) pretty picture:

This was so simple, I’m almost embarrassed to post it, but it will probably be helpful for me later, so here it is.  What is it?  I pretended I had two little pingers spaced 5 wavelengths apart, sending out continuous sinusoidal waves.  I summed these signals at each of the elements in a 2-D grid, plotted the resulting magnitudes, and voila.

What I had to learn:

- How to use exp() using numpy – I had to load it separately for some reason, otherwise it would default to the exp() that comes with the basic math package, which doesn’t allow computations on arrays.

-How to plot an image, a la “imagesc” in Matlab.  This is accomplished using <code>imshow(datahere)</code>, and a colorbar can be added using <code>colorbar()</code>.

-How to do a screen capture of a certain area on a Mac computer:  command+shift+4 gives you crosshairs so you can pick what you like.

It would have been nice to add some attenuation, but I’m too tired now.  One more thing that I need to figure out though, what’s the best way to post my code?  I probably should figure out how to put it up on the bluehost server (where this blog lives), and link to it from here.

More ray tracing – doing it right this time

Okay, enough of me and my hack methods of ray tracing.  I’m going to do it right this time.  And in Python.  I’m starting by working with Val – he was kind enough to send me his Matlab ray tracing code, which is very similar to what I would like to do, although he hasn’t exactly designed it for bathymetric purposes.  But hey, ray tracing is ray tracing, right?  So I’m starting out by looking at his code – I love reading through Val’s code, it’s like reading a book.  So well commented!  And so thorough in the background explanations.  Even my little pea brain can understand most of it.  Also, for reference, I’m reading the ray tracing section of “Principles of Underwater Sound” by Robert J. Urick (1983) – p. 123-126 mostly.

One thing that Val mentioned about his Matlab code was that he had a bug in it that cropped up whenever the launch angles of the rays started above the horizontal.  He wanted me to look at it and see if I could find the problem.

Matlab on iPhone!

Okay, it’s actually just a way to connect remotely to Matlab running on your computer, but still – very cool!  Will there be one for Python??  :-)

Matlab for iPhone

Matlab Dynamic Date Ticks

I got this tip from Val, and as he said, it sounds great if it’s works as advertised. Anyone who has used Matlab’s datetick function to plot dates on the figure axes knows how it can be a pain. But check it out at Matlab Central. Here’s a description of this function from the website:

DYNAMICDATETICKS is a wrapper function around DATETICK which creates dynamic date tick labels for plots with dates on the X-axis. Features include:

* Smart ticks: Include year/month/day information on specific ticks as appropriate.
* Dynamic ticks: Ticks update as the plot is panned or zoomed
* Scaling ticks: Ticks change format as the timescale changes (from years to seconds).
* Support for multiple axes: Supports any combination of date and non-date axes as well as linked axes
* Date-friendly data tips: Dates displayed correctly on data cursors.

USAGE:

dynamicDateTicks()
makes the current axes a date axes with dynamic properties

dynamicDateTicks(axH)
makes all the axes handles in vector axH dynamic date axes

dynamicDateTicks(axH, ‘linked’)
additionally specifies that all the axes in axH are linked. This
option should be used in conjunction with LINKAXES.

EXAMPLES:
load integersignal
dates = datenum(‘July 1, 2008′):1/24:datenum(‘May 11, 2009 1:00 PM’);
subplot(2,1,1), plot(dates, Signal1);
dynamicDateTicks
subplot(2,1,2), plot(dates, Signal4);
dynamicDateTicks

figure
ax1 = subplot(2,1,1); plot(dates, Signal1);
ax2 = subplot(2,1,2); plot(dates, Signal4);
linkaxes([ax1 ax2], ‘x’);
dynamicDateTicks([ax1 ax2], ‘linked’)

Synchronize axis limits in Matlab

This is a handy little trick to know when making plots with subplots in Matlab.  It’s really easy, too.

Here’s an example (taken from the link below):
ax(1) = subplot(2,2,1);
plot(rand(1,10)*10,'Parent',ax(1));
ax(2) = subplot(2,2,2);
plot(rand(1,10)*100,'Parent',ax(2));
linkaxes(ax,'x');

http://www.mathworks.com/access/helpdesk/help/techdoc/ref/linkaxes.html

Whos in Python

Probably my most frequently used Matlab command is the “whos” command – it’s great for debugging.  A quick way to check on the variables in your Matlab workspace.

According to the comments here, it seems like it should work in iPython in a very similar way.  It looks like the main difference is that you get way more than what you would normally get in Matlab.  In Matlab you would just get all of the variables in the workspace, but in iPython, you get the variables, functions, objects, etc (which I don’t want!)… but you should be able to type “whos array” or “whos function” to restrict the search.

Unfortunately I can’t test this until next week when I’m back home and have access to my laptop.  Hopefully it does the trick!

FFT Review

I haven’t done signal processing of any sort for a while now (that’s not to say I ever did very much of it) – but I occasionally find myself needing to do some filtering or frequency spectrum analysis. And as usual, I always need to look up how I did it before. I should really write myself a little cheat sheet. But since I don’t have time for that now, here’s a quick link: FFT Tutorial. It’s from someone in the EE department at the University of Rhode Island. I had a quick look and I like it because it provides some theory, and also a Matlab example (and it’s pretty clearly written using LaTeX – yeah!). And while I’m on the topic of signal processing, here’s a link to a tutorial by Richard Lyons: “Quadrature Signals, Complex but not Complicated“. I like this one because it has a movie trivia question on page 3. And I totally knew the answer without looking.

Interpolation using Scipy/Numpy

As part of a little script I’m writing, I need to do some simple linear interpolation. The Matlab equivalent of what I’m doing is called ‘interp1′. So far I’ve come across two ways to do 1-d, linear interpolation. One is ‘interp’ in numpy. The other is ‘interp1d’ in scipy.interpolate. I’m not completely sure of the difference. Is one faster? Is one older? I’ve googled around a bit, but still haven’t found a clear answer. For now, I’ve implemented ‘interp1d’, which is less similar to Matlab’s ‘interp1′. You first define an interpolated object given your x and y vectors. Then you call that object with your new x-values to generate the new y-values.

And here is an example, chopped out of my code:

depthvector1 = r_[0:nadirdepth:DepthIncrement]
interpfun1 = interp1d(depth1,ssp1) # my x and y vectors
sspvector1 = interpfun1(depthvector1) # find the new y's for this x

"Repmat" function in Numpy/Scipy?

I’m such a Matlab user. I just want to repeat an array or matrix X times, which I can do easily in Matlab using ‘repmat’. I’m sure this is super easy, and I’m just not seeing something obvious. Any tips? Is it something like concatenating copies of an array with itself? vstack?

Hey – I just found what I was looking for: I can do what I need to do here using the ’tile’ function in numpy. It works like this:

from numpy import *

x = array([1,2]) # create a simple array
bigx = tile(x,(2,1))

And the output is:
array([[1,2],
[1,2]])

Awesome! Now I can get rid of those pesky nested loops!

Also something interesting that I just discovered while messing with this in iPython: even if ‘x’ in this example is not created as an array (say it’s a list or a tuple) – it doesn’t matter – numpy still understands it, and then outputs an array object! Amazing. :-)

Reverse axis direction in Pylab

I have been trying to remember how to do this FOREVER! I’m trying to plot a sound speed profile with depth along the y-axis and sound speed along the x-axis. But if I don’t reverse axes, the depth increases up, which isn’t really very intuitive.  In Matlab, it’s pretty easy.  But how to do it in Python/Pylab?  Here’s what the plot looked like before reversing the y-axis.

Here’s the code I used to reverse the axis:

from pylab import *

### SKIPPING SOME CODE HERE

# Plot sound speed profiles
plot(sspvector1,(depthvector1))
plot(sspvector2,(depthvector2),'r')

# Reverse the y-axis
ax = gca()
ax.set_ylim(ax.get_ylim()[::-1])

title('Sound speed profiles')
xlabel('Sound speed (m/s)')
ylabel('Depth (m)')
grid()
show()

And here’s the result: