From Matlab to Python 
[Feb. 27th, 201305:38 pm]
Tobin Fricke's Lab Notebook

Since college, Matlab has been my goto environment for all kinds of numerical simulations, analysis, and plotting. Matlab is an exceptionally welldesigned environment and I love it.
The downside to Matlab is that it is expensive. Happily my employer provides not only a Matlab license but also licenses to the many addon toolboxes that quickly become indispensable. Nonetheless, since the license server is on the network, work grinds to a halt when sitting with the laptop on a train or an airplane or anywhere else without network access.
I've heard tell that many of the useful features of Matlab have been ported over to Python. The idea of a free, opensource environment that's just as good as Matlab is very appealing. To be honest, I'm not really sure what's needed to make this Python environment work, or really, what all the pieces are. I've heard of matplotlib (for making Matlablike plots), SciPy, NumPy, and Pylab. Here's a first notebook entry in trying to sort all of this out.
Here's what I have so far:
First, install "matplotlib" and numerical python ("numpy"). Matplotlib is the package that lets us make nice Matlabstyle plots, and numpy contains lots of Matlablike numerical functions. They work together... somehow. On Ubuntu, installation is just one shell command:sudo aptget install pythonmatplotlib pythonnumpy As a first simple task, let's plot an Airy function. Here's my equivalent Matlab script:
% Matlab code to plot a cavity resonance
F = 10; % Finesse
f = linspace(0.5, 1.5, 201); P = 1./(1 + (2/pi) * F^2 * sin(pi*f).^2);
plot(f, P); xlabel('free spectral ranges'); ylabel('power buildup'); And now the python:# Python code to plot a cavity resonance
import numpy as numpy F = 10 f = numpy.linspace(0.5, 1.5, 201) P = 1 / (1 + (2/numpy.pi) * F**2 * numpy.sin(numpy.pi * f) ** 2)
import matplotlib.pyplot as plt plt.plot(f, P) plt.xlabel("free spectral ranges") plt.ylabel("power buildup") plt.show() The package names (numpy and plt) make that code a bit verbose and cumbersome. I'm not sure whether it's considered good style, but it's possible to import numpy and the plotting library into the default namespace. The resulting code is almost exactly the same as Matlab, except the power operator is ** instead of ^ and you need to call show() to make the plot appear. Also, the regular division operator seems to work in Python (instead of Matlab's elementwise ./ operator).
# Python! from numpy import * from matplotlib.pyplot import * F = 10 f = linspace(0.5, 1.5, 201) P = 1/ (1 + (2/pi) * F**2 * sin(pi*f)**2) plot(f, P) xlabel("free spectral ranges") ylabel("power buildup") show() To run that, I just started the regular python interpreter (by typing "python" at a command prompt) and typed it in by hand.
The results:
That's Matlab's plot window on the left, and Python's Matplotlib on the right. Not bad! 

