MATLAB commands in numerical Python 1 Vidar Bronken Gundersen /mathesaurus.sf.net IDL commands in numerical Python Copyright c Vidar Bronken Gundersen Permission is granted to copy, distribute and/or modify this document as long as the above attribution is kept and the resulting work is distributed under a license identical to this one. Contributor: Gary Ruben The idea of this document (and the corresponding xml instance) is to provide a quick reference for switching from idl to an open-source environment, such as gdl, Python, R or Octave and Gnuplot for numeric processing and data visualisation. Time-stamp: --T::vidar 1 Help Desc. IDL Python matlab/Octave Browse help interactively ? help() doc Octave: help -i % browse with Info Help on using help ?help help help help or doc doc Help for a function ?plot or man,’plot help(plot) or ?plot help plot Help for a toolbox/library package help(pylab) help splines or doc splines Demonstration examples demo demo 1.1 Searching available documentation Desc. IDL Python matlab/Octave Search help files lookfor plot List available packages help(); modules [Numeric] help Locate functions help(plot) which plot 1.2 Using interactively Desc. IDL Python matlab/Octave Start session idlde ipython -pylab Octave: octave -q Auto completion TAB Octave: TAB or M-? Run code from file @"foo.idlbatch" or .run ’foo.pro’ execfile(’foo.py’) or run foo.py foo(.m) Command history help,/rec hist -n Octave: history Save command history journal,’IDLhistory’ diary on [..] diary off End session exit or CTRL-D CTRL-D CTRL-Z # windows sys.exit() exit or quit 2 Operators Desc. IDL Python matlab/Octave Help on operator syntax help - References: Hankin, Robin. R for Octave users (), available from http://cran.r-project.org/doc/contrib/R-and-octave-.txt (accessed ..); Martelli, Alex. Python in a Nutshell (O’Reilly, ); Oliphant, Travis. Guide to NumPy (Trelgol, ); Hunter, John. The Matplotlib User’s Guide (), available from http://matplotlib.sf.net/ (accessed ..); Langtangen, Hans Petter. Python Scripting for Computational Science (Springer, ); Ascher et al.: Numeric Python manual (), available from http://numeric.scipy.org/numpy.pdf (accessed ..); Moler, Cleve. Numerical Computing with MATLAB (MathWorks, ), available from http://www.mathworks.com/moler/ (accessed ..); Eaton, John W. Octave Quick Reference (); Merrit, Ethan. Demo scripts for gnuplot version 4.0 (), available from http://gnuplot.sourceforge.net/demo/ (accessed ..); Woo, Alex. Gnuplot Quick Reference (), available from http://www.gnuplot.info/docs/gpcard.pdf (accessed ..); Venables & Smith: An Introduction to R (), available from http://cran.r-project.org/doc/manuals/R-intro.pdf (accessed ..); Short, Tom. R reference card (), available from http://www.rpad.org/Rpad/R-refcard.pdf (accessed ..); Greenfield, Jedrzejewski & Laidler. Using Python for Interactive Data Analysis (), pp.–, available from http://stsdas.stsci.edu/perry/pydatatut.pdf (accessed ..); Brisson, Eric. Using IDL to Manipulate and Visualize Scientific Data, available from http://scv.bu.edu/Tutorials/IDL/ (accessed ..).
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
MATLAB commands in numerical Python 1Vidar Bronken Gundersen /mathesaurus.sf.net
The idea of this document (and the corresponding xml instance) is to provide a quick reference for switching from idlto an open-source environment, such as gdl, Python, R or Octave and Gnuplot for numeric processing and data visualisation.
Time-stamp: --T:: vidar
1 Help
Desc. IDL Python matlab/OctaveBrowse help interactively ? help() doc
Octave: help -i % browse with InfoHelp on using help ?help help help help or doc docHelp for a function ?plot or man,’plot help(plot) or ?plot help plotHelp for a toolbox/library package help(pylab) help splines or doc splinesDemonstration examples demo demo
1.1 Searching available documentation
Desc. IDL Python matlab/OctaveSearch help files lookfor plotList available packages help(); modules [Numeric] helpLocate functions help(plot) which plot
1.2 Using interactively
Desc. IDL Python matlab/OctaveStart session idlde ipython -pylab Octave: octave -qAuto completion TAB Octave: TAB or M-?Run code from file @"foo.idlbatch" or .run ’foo.pro’ execfile(’foo.py’) or run foo.py foo(.m)Command history help,/rec hist -n Octave: historySave command history journal,’IDLhistory’ diary on [..] diary offEnd session exit or CTRL-D CTRL-D
CTRL-Z # windowssys.exit()
exit or quit
2 Operators
Desc. IDL Python matlab/OctaveHelp on operator syntax help -
References: Hankin, Robin. R for Octave users (), available from http://cran.r-project.org/doc/contrib/R-and-octave-.txt (accessed ..); Martelli, Alex. Python in a Nutshell (O’Reilly, );Oliphant, Travis. Guide to NumPy (Trelgol, ); Hunter, John. The Matplotlib User’s Guide (), available from http://matplotlib.sf.net/ (accessed ..); Langtangen, Hans Petter. PythonScripting for Computational Science (Springer, ); Ascher et al.: Numeric Python manual (), available from http://numeric.scipy.org/numpy.pdf (accessed ..); Moler, Cleve. NumericalComputing with MATLAB (MathWorks, ), available from http://www.mathworks.com/moler/ (accessed ..); Eaton, John W. Octave Quick Reference (); Merrit, Ethan. Demo scripts forgnuplot version 4.0 (), available from http://gnuplot.sourceforge.net/demo/ (accessed ..); Woo, Alex. Gnuplot Quick Reference (), available from http://www.gnuplot.info/docs/gpcard.pdf(accessed ..); Venables & Smith: An Introduction to R (), available from http://cran.r-project.org/doc/manuals/R-intro.pdf (accessed ..); Short, Tom. R reference card (), availablefrom http://www.rpad.org/Rpad/R-refcard.pdf (accessed ..); Greenfield, Jedrzejewski & Laidler. Using Python for Interactive Data Analysis (), pp.–, available fromhttp://stsdas.stsci.edu/perry/pydatatut.pdf (accessed ..); Brisson, Eric. Using IDL to Manipulate and Visualize Scientific Data, available from http://scv.bu.edu/Tutorials/IDL/ (accessed ..).
MATLAB commands in numerical Python 2Vidar Bronken Gundersen /mathesaurus.sf.net
2.1 Arithmetic operators
Desc. IDL Python matlab/OctaveAssignment; defining a number a=1 & b=1 a=1; b=1 a=1; b=2;Addition a + b a + b or add(a,b) a + bSubtraction a - b a - b or subtract(a,b) a - bMultiplication a * b a * b or multiply(a,b) a * bDivision a / b a / b or divide(a,b) a / b
Power, ab a ^ b a ** bpower(a,b)pow(a,b)
a .^ b
Remainder a MOD b a % bremainder(a,b)fmod(a,b)
rem(a,b)
Increment, return new value ++a or a+=1 Octave: ++aIncrement, return old value a++ Octave: a++In place operation to save array creationoverhead
a+=1 a+=b or add(a,b,a) Octave: a+=1
Factorial, n! factorial(a)
2.2 Relational operators
Desc. IDL Python matlab/OctaveEqual a eq b a == b or equal(a,b) a == bLess than a lt b a < b or less(a,b) a < bGreater than a gt b a > b or greater(a,b) a > bLess than or equal a le b a <= b or less_equal(a,b) a <= bGreater than or equal a ge b a >= b or greater_equal(a,b) a >= bNot Equal a ne b a != b or not_equal(a,b) a ~= b
2.3 Logical operators
Desc. IDL Python matlab/OctaveShort-circuit logical AND a and b a && bShort-circuit logical OR a or b a || bElement-wise logical AND a and b logical_and(a,b) or a and b a & b or and(a,b)Element-wise logical OR a or b logical_or(a,b) or a or b a | b or or(a,b)Logical EXCLUSIVE OR a xor b logical_xor(a,b) xor(a, b)Logical NOT not a logical_not(a) or not a ~a or not(a)
Octave: ~a or !aTrue if any element is nonzero any(a)True if all elements are nonzero all(a)
Logarithm, base e (natural) alog(a) math.log(a) log(a) ln a = loge aLogarithm, base alog10(a) math.log10(a) log10(a) log10 aLogarithm, base (binary) math.log(a, 2) log2(a) log2 aExponential function exp(a) math.exp(a) exp(a) ea
MATLAB commands in numerical Python 3Vidar Bronken Gundersen /mathesaurus.sf.net
2.5 Round offDesc. IDL Python matlab/OctaveRound round(a) around(a) or math.round(a) round(a)Round up ceil(a) ceil(a) ceil(a)Round down floor(a) floor(a) floor(a)Round towards zero fix(a) fix(a)
2.6 Mathematical constantsDesc. IDL Python matlab/Octaveπ = 3.141592 !pi math.pi pie = 2.718281 exp(1) math.e or math.exp(1) exp(1)
2.6.1 Missing values; IEEE-754 floating point status flags
Desc. IDL Python matlab/OctaveNot a Number nan NaNInfinity, ∞ inf InfInfinity, +∞ plus_infInfinity, −∞ minus_infPlus zero, +0 plus_zeroMinus zero, −0 minus_zero
2.7 Complex numbers
Desc. IDL Python matlab/OctaveImaginary unit complex(0,1) z = 1j i i =
√−1
A complex number, 3 + 4i z = complex(3,4) z = 3+4j or z = complex(3,4) z = 3+4iAbsolute value (modulus) abs(z) abs(3+4j) abs(z)Real part real_part(z) z.real real(z)Imaginary part imaginary(z) z.imag imag(z)Argument arg(z)Complex conjugate conj(z) z.conj(); z.conjugate() conj(z)
3.4 Miss those elements outDesc. IDL Python matlab/Octavemiss the first element a[1:] a(2:end)miss the tenth element a([1:9])last element a[-1] a(end)last two elements a[-2:] a(end-1:end)
3.5 Maximum and minimumDesc. IDL Python matlab/Octavepairwise max maximum(a,b) max(a,b)max of all values in two vectors concatenate((a,b)).max() max([a b])
v,i = a.max(0),a.argmax(0) [v,i] = max(a)
MATLAB commands in numerical Python 5Vidar Bronken Gundersen /mathesaurus.sf.net
3.6 Vector multiplication
Desc. IDL Python matlab/OctaveMultiply two vectors a*a a.*aVector cross product, u× v crossp(u,v)Vector dot product, u · v dot(u,v) dot(u,v)
4 MatricesDesc. IDL Python matlab/Octave
Define a matrix a = [[2,3],[4,5]] a = array([[2,3],[4,5]]) a = [2 3;4 5]
4.8 SumDesc. IDL Python matlab/OctaveSum of each column total(a,2) a.sum(axis=0) sum(a)Sum of each row total(a,1) a.sum(axis=1) sum(a’)Sum of all elements total(a) a.sum() sum(sum(a))Sum along diagonal a.trace(offset=0)Cumulative sum (columns) a.cumsum(axis=0) cumsum(a)
4.9 Sorting
Desc. IDL Python matlab/Octave
Example data a = array([[4,3,2],[2,8,6],[1,4,7]]) a = [ 4 3 2 ; 2 8 6 ; 1 4 7 ]
[4 3 22 8 61 4 7
]Flat and sorted a.ravel().sort() or sort(a(:))
[1 2 23 4 46 7 8
]Sort each column sort(a) a.sort(axis=0) or msort(a) sort(a)
[1 3 22 4 64 8 7
]Sort each row a.sort(axis=1) sort(a’)’
[2 3 42 6 81 4 7
]Sort rows (by first row) a[a[:,0].argsort(),] sortrows(a,1)
[1 4 72 8 64 3 2
]Sort, return indices a.ravel().argsort()Sort each column, return indices a.argsort(axis=0)Sort each row, return indices a.argsort(axis=1)
MATLAB commands in numerical Python 8Vidar Bronken Gundersen /mathesaurus.sf.net
4.10 Maximum and minimumDesc. IDL Python matlab/Octavemax in each column max(a,DIMENSION=2) a.max(0) or amax(a [,axis=0]) max(a)max in each row max(a,DIMENSION=1) a.max(1) or amax(a, axis=1) max(a’)max in array max(a) a.max() or max(max(a))return indices, i [v i] = max(a)pairwise max maximum(b,c) max(b,c)
cummax(a)max-to-min range a.ptp(); a.ptp(0)
4.11 Matrix manipulation
Desc. IDL Python matlab/OctaveFlip left-right reverse(a) fliplr(a) or a[:,::-1] fliplr(a)Flip up-down reverse(a,2) flipud(a) or a[::-1,] flipud(a)Rotate degrees rotate(a,1) rot90(a) rot90(a)Repeat matrix: [ a a a ; a a a ] kron(ones((2,3)),a) repmat(a,2,3)
Desc. IDL Python matlab/OctaveMatrix dimensions size(a) a.shape or a.getshape() size(a)Number of columns s=size(a) & s[1] a.shape[1] or size(a, axis=1) size(a,2) or length(a)Number of elements n_elements(a) a.size or size(a[, axis=None]) length(a(:))Number of dimensions a.ndim ndims(a)Number of bytes used in memory a.nbytes
4.13 Matrix- and elementwise- multiplication
Desc. IDL Python matlab/Octave
Elementwise operations a * b or multiply(a,b) a .* b
[1 59 16
]Matrix product (dot product) a # b or b ## a matrixmultiply(a,b) a * b
[7 10
15 22
]Inner matrix vector multiplication a · b′ transpose(a) # b inner(a,b) or
[5 11
11 25
]Outer product a # b outer(a,b) or
[1 2 3 42 4 6 83 6 9 124 8 12 16
]
Kronecker product kron(a,b) kron(a,b)
[1 2 2 43 4 6 83 6 4 89 12 12 16
]Matrix division, b·a−1 a / b
Left matrix division, b−1·a(solve linear equations)
MATLAB commands in numerical Python 9Vidar Bronken Gundersen /mathesaurus.sf.net
4.14 Find; conditional indexing
Desc. IDL Python matlab/OctaveNon-zero elements, indices a.ravel().nonzero() find(a)
Non-zero elements, array indices where(a NE 0) (i,j) = a.nonzero()(i,j) = where(a!=0)
[i j] = find(a)
Vector of non-zero values a(where(a NE 0)) v = a.compress((a!=0).flat)v = extract(a!=0,a)
[i j v] = find(a)
Condition, indices where(a GE 5.5) (a>5.5).nonzero() find(a>5.5)
Return values a(where(a GE 5.5)) a.compress((a>5.5).flat)
Zero out elements above . where(a>5.5,0,a) or a * (a>5.5) a .* (a>5.5)Replace values a.put(2,indices)
5 Multi-way arrays
Desc. IDL Python matlab/OctaveDefine a -way array a = array([[[1,2],[1,2]], [[3,4],[3,4]]])a = cat(3, [1 2; 1 2],[3 4; 3 4]);
a[0,...] a(1,:,:)
6 File input and output
Desc. IDL Python matlab/OctaveReading from a file (d) read() f = fromfile("data.txt")
f = load("data.txt")f = load(’data.txt’)
Reading from a file (d) read() f = load("data.txt") f = load(’data.txt’)Reading fram a CSV file (d) x = read_ascii(data_start=1,delimiter=’;’)f = load(’data.csv’, delimiter=’;’) x = dlmread(’data.csv’, ’;’)Writing to a file (d) save(’data.csv’, f, fmt=’%.6f’, delimiter=’;’)save -ascii data.txt fWriting to a file (d) f.tofile(file=’data.csv’, format=’%.6f’, sep=’;’)Reading from a file (d) f = fromfile(file=’data.csv’, sep=’;’)
MATLAB commands in numerical Python 10Vidar Bronken Gundersen /mathesaurus.sf.net
7 Plotting
7.1 Basic x-y plots
Desc. IDL Python matlab/Octave
d line plot plot, a plot(a) plot(a)0 20 40 60 80 100
MATLAB commands in numerical Python 16Vidar Bronken Gundersen /mathesaurus.sf.net
10 Programming
Desc. IDL Python matlab/OctaveScript file extension .idlbatch .py .mComment symbol (rest of line) ; # %
Octave: % or #Import library functions from pylab import * % must be in MATLABPATH
Octave: % must be in LOADPATHEval string="a=234"
eval(string)string=’a=234’;eval(string)
10.1 Loops
Desc. IDL Python matlab/Octavefor-statement for k=1,5 do print,k for i in range(1,6): print(i) for i=1:5; disp(i); endMultiline for statements for k=1,5 do begin $
print, i &$print, i*2 &$
end
for i in range(1,6):print(i)print(i*2)
for i=1:5disp(i)disp(i*2)
end
10.2 ConditionalsDesc. IDL Python matlab/Octaveif-statement if 1 gt 0 then a=100 if 1>0: a=100 if 1>0 a=100; endif-else-statement if 1 gt 0 then a=100 else a=0 if 1>0 a=100; else a=0; endTernary operator (if?true:false) a>0?a:0 a > 0?a : 0
10.3 Debugging
Desc. IDL Python matlab/OctaveMost recent evaluated expression ansList variables loaded into memory help whos or whoClear variable x from memory clear x or clear [all]Print print, a print a disp(a)
10.4 Working directory and OS
Desc. IDL Python matlab/OctaveList files in directory dir os.listdir(".") dir or lsList script files in directory grep.grep("*.py") whatDisplays the current working directory sd os.getcwd() pwdChange working directory cd,’foo or sd,’foo os.chdir(’foo’) cd fooInvoke a System Command spawn,’notepad’ os.system(’notepad’)
This document is still draft quality. Most shown d plots are made using Matplotlib, and d plots using R and Gnuplot, provided as examples only.Version numbers and download url for software used: Python .., http://www.python.org/; NumPy .., http://numeric.scipy.org/; Matplotlib ., http://matplotlib.sf.net/; IPython ..,
http://ipython.scipy.org/; Octave .., http://www.octave.org/; Gnuplot ., http://www.gnuplot.info/.For referencing: Gundersen, Vidar Bronken. MATLAB commands in numerical Python (Oslo/Norway, ), available from: http://mathesaurus.sf.net/Contributions are appreciated: The best way to do this is to edit the xml and submit patches to our tracker or forums.