Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net IDL commands in numerical Python c Copyright 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. Browse help interactively IDL ? Python help() Help on using help Help for a function Help for a toolbox/library package Demonstration examples ?help ?plot or man,’plot help help(plot) or ?plot help(pylab) 1.1 Searching available documentation Desc. Search help files List available packages Locate functions 1.2 IDL Python help(); modules [Numeric] help(plot) matlab/Octave lookfor plot help which plot Using interactively Desc. Start session Auto completion Run code from file Command history Save command history End session 2 demo matlab/Octave doc Octave: help -i % browse with Info help help or doc doc help plot help splines or doc splines demo IDL idlde @"foo.idlbatch" or .run ’foo.pro’ help,/rec journal,’IDLhistory’ exit or CTRL-D Python ipython -pylab TAB execfile(’foo.py’) or run foo.py hist -n CTRL-D CTRL-Z # windows sys.exit() matlab/Octave Octave: octave -q Octave: TAB or M-? foo(.m) Octave: history diary on [..] diary off exit or quit Operators Desc. Help on operator syntax IDL Python matlab/Octave 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 ..). 1 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 2.1 Arithmetic operators Desc. Assignment; defining a number Addition Subtraction Multiplication Division Power, ab IDL a=1 & b=1 a + b a - b a * b a / b a ^ b Remainder a MOD b Increment, return new value Increment, return old value In place operation to save array creation overhead Factorial, n! ++a or a+=1 a++ a+=1 2.2 a+=b or add(a,b,a) rem(a,b) Octave: ++a Octave: a++ Octave: a+=1 factorial(a) IDL a eq a lt a gt a le a ge a ne b b b b b b Python a == b or equal(a,b) a < b or less(a,b) a > b or greater(a,b) a <= b or less_equal(a,b) a >= b or greater_equal(a,b) a != b or not_equal(a,b) matlab/Octave a == b a < b a > b a <= b a >= b a ~= b Python a and b a or b logical_and(a,b) or a and b logical_or(a,b) or a or b logical_xor(a,b) logical_not(a) or not a matlab/Octave a && b a || b a & b or and(a,b) a | b or or(a,b) xor(a, b) ~a or not(a) Octave: ~a or !a any(a) all(a) Python math.sqrt(a) math.log(a) math.log10(a) math.log(a, 2) math.exp(a) matlab/Octave sqrt(a) log(a) log10(a) log2(a) exp(a) Logical operators Desc. Short-circuit logical AND Short-circuit logical OR Element-wise logical AND Element-wise logical OR Logical EXCLUSIVE OR Logical NOT IDL a and b a or b a xor b not a True if any element is nonzero True if all elements are nonzero 2.4 matlab/Octave a=1; b=2; a + b a - b a * b a / b a .^ b Relational operators Desc. Equal Less than Greater than Less than or equal Greater than or equal Not Equal 2.3 Python a=1; b=1 a + b or add(a,b) a - b or subtract(a,b) a * b or multiply(a,b) a / b or divide(a,b) a ** b power(a,b) pow(a,b) a % b remainder(a,b) fmod(a,b) root and logarithm Desc. Square root Logarithm, base e (natural) Logarithm, base Logarithm, base (binary) Exponential function IDL sqrt(a) alog(a) alog10(a) exp(a) √ a ln a = loge a log10 a log2 a ea 2 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 2.5 Round off Desc. Round Round up Round down Round towards zero 2.6 Python math.pi math.e or math.exp(1) matlab/Octave pi exp(1) IDL Python nan inf plus_inf minus_inf plus_zero minus_zero matlab/Octave NaN Inf IDL complex(0,1) z = complex(3,4) abs(z) real_part(z) imaginary(z) Python z = 1j z = 3+4j or z = complex(3,4) abs(3+4j) z.real z.imag conj(z) z.conj(); z.conjugate() matlab/Octave i z = 3+4i abs(z) real(z) imag(z) arg(z) conj(z) IDL Python atan2(b,a) matlab/Octave atan(a,b) IDL !pi exp(1) Complex numbers Desc. Imaginary unit A complex number, 3 + 4i Absolute value (modulus) Real part Imaginary part Argument Complex conjugate 2.8 matlab/Octave round(a) ceil(a) floor(a) fix(a) Missing values; IEEE-754 floating point status flags Desc. Not a Number Infinity, ∞ Infinity, +∞ Infinity, −∞ Plus zero, +0 Minus zero, −0 2.7 Python around(a) or math.round(a) ceil(a) floor(a) fix(a) Mathematical constants Desc. π = 3.141592 e = 2.718281 2.6.1 IDL round(a) ceil(a) floor(a) √ −1 Trigonometry Desc. Arctangent, arctan(b/a) Hypotenus; Euclidean distance 2.9 i= p hypot(x,y) Generate random numbers Desc. Uniform distribution IDL randomu(seed, 10) Python random.random((10,)) random.uniform((10,)) matlab/Octave rand(1,10) Uniform: Numbers between and 2+5*randomu(seed, 10) random.uniform(2,7,(10,)) 2+5*rand(1,10) Uniform: , array randomu(seed,[6,6]) random.uniform(0,1,(6,6)) rand(6) Normal distribution randomn(seed, 10) random.standard_normal((10,)) randn(1,10) x2 + y 2 3 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 3 Vectors Desc. Row vector, 1 × n-matrix Column vector, m × 1-matrix 3.1 .,.,., ... ,. ,,, ,,, ... , ,,, Linearly spaced vector of n= points Reverse Set all values to same scalar value Python arange(1,11, dtype=Float) range(1,11) arange(10.) arange(1,11,3) arange(10,0,-1) arange(10,0,-3) linspace(1,10,7) a[::-1] or a.fill(3), a[:] = 3 matlab/Octave 1:10 0:9 1:3:10 10:-1:1 10:-3:1 linspace(1,10,7) reverse(a) a(:) = 3 IDL [a,a] or rebin(a,2,size(a)) [indgen(3)+1,a] Python concatenate((a,a)) concatenate((range(1,5),a), axis=1) matlab/Octave [a a] [1:4 a] IDL Python concatenate((a,a)) a.repeat(3) or a.repeat(a) or matlab/Octave [a a] Python a[1:] a[-1] a[-2:] matlab/Octave a(2:end) a([1:9]) a(end) a(end-1:end) Python maximum(a,b) concatenate((a,b)).max() v,i = a.max(0),a.argmax(0) matlab/Octave max(a,b) max([a b]) [v,i] = max(a) reverse(a) Miss those elements out Desc. miss the first element miss the tenth element last element last two elements 3.5 IDL indgen(10)+1 dindgen(10)+1 dindgen(10) indgen(4)*3+1 Repeating Desc. , , , , , 3.4 matlab/Octave a=[2 3 4 5]; adash=[2 3 4 5]’; Concatenation (vectors) Desc. Concatenate two vectors 3.3 Python a=array([2,3,4,5]) array([2,3,4,5])[:,NewAxis] array([2,3,4,5]).reshape(-1,1) r_[1:10,’c’] Sequences Desc. ,,, ... , 3.2 IDL a = [2, 3, 4, 5] transpose([2,3,4,5]) IDL Maximum and minimum Desc. pairwise max max of all values in two vectors IDL 4 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 3.6 Vector multiplication Desc. Multiply two vectors Vector cross product, u × v Vector dot product, u · v 4 IDL Python a*a matlab/Octave a.*a dot(u,v) dot(u,v) crossp(u,v) Matrices Desc. IDL Python matlab/Octave Define a matrix a = [[2,3],[4,5]] a = array([[2,3],[4,5]]) a = [2 3;4 5] 4.1 2 4 3 5 i 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 9 9 9 1 0 0 4 0 0 8 3 4 1 1 1 9 9 9 0 1 0 0 5 0 1 5 9 1 1 1 9 9 9 0 0 1 0 0 6 6 7 2 1 1 1 9 9 9 1 1 1 9 9 9 Concatenation (matrices); rbind and cbind Desc. Bind rows IDL Python matlab/Octave concatenate((a,b), axis=0) [a ; b] vstack((a,b)) concatenate((a,b), axis=1) [a , b] hstack((a,b)) concatenate((a,b), axis=2) dstack((a,b)) concatenate((a,b), axis=None) [a(:), b(:)] concatenate((r_[1:5],r_[1:5])).reshape(2,-1) [1:4 ; 1:4] vstack((r_[1:5],r_[1:5])) [1:4 ; 1:4]’ Desc. IDL Python matlab/Octave filled array dblarr(3,5) zeros((3,5),Float) zeros(3,5) filled array of integers intarr(3,5) zeros((3,5)) filled array dblarr(3,5)+1 ones((3,5),Float) Any number filled array intarr(3,5)+9 Identity matrix identity(3) identity(3) eye(3) Diagonal diag_matrix([4,5,6]) diag((4,5,6)) diag([4 5 6]) Bind columns Bind slices (three-way arrays) Concatenate matrices into one vector Bind rows (from vectors) Bind columns (from vectors) 4.2 h Array creation ones(3,5) ones(3,5)*9 Magic squares; Lo Shu Empty array magic(3) a = empty((3,3)) 5 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 4.3 Reshape and flatten matrices Desc. IDL Python matlab/Octave Reshaping (rows first) reform(a,2,3) arange(1,7).reshape(2,-1) a.setshape(2,3) reshape(1:6,3,2)’; Reshaping (columns first) arange(1,7).reshape(-1,2).transpose() reshape(1:6,2,3); Flatten to vector (by rows, like comics) a.flatten() or a’(:) Flatten to vector (by columns) a.flatten(1) a(:) Flatten upper triangle (by columns) 4.4 1 4 2 5 3 6 i h 1 2 3 4 5 6 i 1 2 3 4 5 6 1 4 2 5 3 6 vech(a) IDL Python b = a.copy() matlab/Octave b = a Indexing and accessing elements (Python: slicing) Desc. IDL Python matlab/Octave Input is a , array Element , (row,col) First row a = [[ 11, 12, 13, 14 ], $ [ 21, 22, 23, 24 ], $ [ 31, 32, 33, 34 ]] a(2,1) a(*,0) a = array([[ 11, 12, 13, 14 ], [ 21, 22, 23, 24 ], [ 31, 32, 33, 34 ]]) a[1,2] a[0,] a = [ 11 12 13 14 ... 21 22 23 24 ... 31 32 33 34 ] a(2,3) a(1,:) First column a(0,*) a[:,0] a(:,1) a.take([0,2]).take([0,3], axis=1) a([1 3],[1 4]); a[1:,] a(2:end,:) Last two rows a[-2:,] a(end-1:end,:) Strides: Every other row a[::2,:] a(1:2:end,:) Third in last dimension (axis) a[...,2] Array as indices All, except first row h a(*,1:*) h h Remove one column a.take([0,2,3],axis=1) Diagonal a.diagonal(offset=0) a(:,[1 3 4]) Assignment Desc. IDL Clipping: Replace all elements over a>90 Clip upper and lower values a < 2 > 5 Python a[:,0] = 99 a[:,0] = array([99,98,97]) (a>90).choose(a,90) a.clip(min=None, max=90) a.clip(min=2, max=5) matlab/Octave a(:,1) = 99 a(:,1) = [99 98 97]’ a(a>90) = 90; a11 a21 a31 a 23 a11 a11 a21 h a31 a11 a31 4.6 Shared data (slicing) Desc. Copy of a 4.5 h a12 a22 a32 a13 a23 a33 a14 a24 a34 a12 a13 a14 a24 a34 a24 a34 a14 a34 i a14 a34 i a21 a31 a21 a31 a11 a31 a22 a32 a22 a32 a12 a32 a23 a33 a23 a33 a13 a33 a11 a21 a31 a11 a13 a23 a33 a22 a14 a24 a34 a33 i i a44 6 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 4.7 Transpose and inverse Desc. Transpose Python a.conj().transpose() matlab/Octave a’ hqr(elmhes(a)) a.transpose() linalg.det(a) or linalg.inv(a) or linalg.pinv(a) norm(a) linalg.eig(a)[0] a.’ or transpose(a) det(a) inv(a) pinv(a) norm(a) eig(a) svdc,A,w,U,V linalg.svd(a) svd(a) Cholesky factorization Eigenvectors linalg.cholesky(a) linalg.eig(a)[1] chol(a) [v,l] = eig(a) Rank rank(a) rank(a) Python a.sum(axis=0) a.sum(axis=1) a.sum() a.trace(offset=0) a.cumsum(axis=0) matlab/Octave sum(a) sum(a’) sum(sum(a)) cumsum(a) Python matlab/Octave Non-conjugate transpose Determinant Inverse Pseudo-inverse Norms Eigenvalues Singular values 4.8 determ(a) invert(a) Sum Desc. Sum of each column Sum of each row Sum of all elements Sum along diagonal Cumulative sum (columns) 4.9 IDL transpose(a) IDL total(a,2) total(a,1) total(a) Sorting Desc. IDL Example data a = array([[4,3,2],[2,8,6],[1,4,7]]) a = [ 4 3 2 ; 2 8 6 ; 1 4 7 ] Flat and sorted a.ravel().sort() or sort(a(:)) a.sort(axis=0) or msort(a) sort(a) Sort each row a.sort(axis=1) sort(a’)’ Sort rows (by first row) a[a[:,0].argsort(),] sortrows(a,1) Sort, return indices Sort each column, return indices Sort each row, return indices a.ravel().argsort() a.argsort(axis=0) a.argsort(axis=1) Sort each column sort(a) 4 2 1 1 3 6 1 2 4 2 2 1 1 2 4 3 8 4 2 4 7 3 4 8 3 6 4 4 8 3 2 6 7 2 4 8 2 6 7 4 8 7 7 6 2 7 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 4.10 Maximum and minimum Desc. max in each column max in each row max in array return indices, i pairwise max IDL max(a,DIMENSION=2) max(a,DIMENSION=1) max(a) maximum(b,c) max-to-min range 4.11 a.ptp(); a.ptp(0) IDL reverse(a) reverse(a,2) rotate(a,1) Triangular, upper Triangular, lower Python fliplr(a) or a[:,::-1] flipud(a) or a[::-1,] rot90(a) kron(ones((2,3)),a) triu(a) tril(a) matlab/Octave fliplr(a) flipud(a) rot90(a) repmat(a,2,3) Octave: kron(ones(2,3),a) triu(a) tril(a) Equivalents to ”size” Desc. Matrix dimensions Number of columns Number of elements Number of dimensions Number of bytes used in memory 4.13 matlab/Octave max(a) max(a’) max(max(a)) [v i] = max(a) max(b,c) cummax(a) Matrix manipulation Desc. Flip left-right Flip up-down Rotate degrees Repeat matrix: [ a a a ; a a a ] 4.12 Python a.max(0) or amax(a [,axis=0]) a.max(1) or amax(a, axis=1) a.max() or IDL size(a) s=size(a) & s[1] n_elements(a) Python a.shape or a.getshape() a.shape[1] or size(a, axis=1) a.size or size(a[, axis=None]) a.ndim a.nbytes matlab/Octave size(a) size(a,2) or length(a) length(a(:)) ndims(a) Matrix- and elementwise- multiplication Desc. IDL Elementwise operations Matrix product (dot product) Inner matrix vector multiplication a · b0 a # b or b ## a transpose(a) # b Python matlab/Octave a * b or multiply(a,b) a .* b matrixmultiply(a,b) a * b h 1 9 h 7 15 5 11 1 2 3 4 1 3 3 9 h inner(a,b) or " Outer product a # b outer(a,b) or " Kronecker product Matrix division, b·a−1 Left matrix division, b−1 ·a (solve linear equations) Vector dot product Cross product cramer(a,b) kron(a,b) kron(a,b) linalg.solve(a,b) a / b a \ b vdot(a,b) cross(a,b) i 5 16 i 10 22 i 11 25 # 2 3 4 4 6 8 6 9 12 8 12 16 # 2 2 4 4 6 8 6 4 8 12 12 16 Ax = b 8 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 4.14 Find; conditional indexing Desc. Non-zero elements, indices IDL Python a.ravel().nonzero() matlab/Octave 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) where(a>5.5,0,a) or a * (a>5.5) a.put(2,indices) Zero out elements above . Replace values 5 Multi-way arrays Desc. Define a -way array 6 a .* (a>5.5) IDL Python matlab/Octave 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,:,:) File input and output Desc. Reading from a file (d) Reading from a file (d) Reading fram a CSV file (d) Writing to a file (d) Writing to a file (d) Reading from a file (d) IDL read() Python matlab/Octave f = fromfile("data.txt") f = load(’data.txt’) f = load("data.txt") read() f = load("data.txt") f = load(’data.txt’) x = read_ascii(data_start=1,delimiter=’;’) f = load(’data.csv’, delimiter=’;’) x = dlmread(’data.csv’, ’;’) save(’data.csv’, f, fmt=’%.6f’, delimiter=’;’) save -ascii data.txt f f.tofile(file=’data.csv’, format=’%.6f’, sep=’;’) f = fromfile(file=’data.csv’, sep=’;’) 9 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 7 Plotting 7.1 Basic x-y plots Desc. IDL Python matlab/Octave 4 3 2 1 0 -1 -2 -3 -4 d line plot plot, a plot(a) 0 20 40 60 80 100 plot(a) 4.5 4.0 3.5 3.0 2.5 2.0 4.0 d scatter plot plot, x(1,*), x(2,*) plot(x[:,0],x[:,1],’o’) 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0 plot(x(:,1),x(:,2),’o’) 7 6 5 4 3 2 1 4.0 Two graphs in one plot Overplotting: Add new plots to current subplots Plotting symbols and color 7.1.1 plot, x1, y1 oplot, x2, y2 !p.multi(0,2,1) plot, x,y, line=1, psym=-1 plot(x1,y1,’bo’, x2,y2,’go’) plot(x1,y1,’o’) plot(x2,y2,’o’) show() # as normal subplot(211) plot(x,y,’ro-’) plot(x1,y1, x2,y2) plot(x1,y1) hold on plot(x2,y2) subplot(211) plot(x,y,’ro-’) matlab/Octave grid on axis equal Octave: axis(’equal’) replot axis([ 0 10 0 5 ]) Axes and titles Desc. Turn on grid lines : aspect ratio IDL Python grid() figure(figsize=(6,6)) Set axes manually plot, x(1,*), x(2,*), xran=[0,10], yran=[0,5] plot, x,y, title=’title’, xtitle=’x-axis’, ytitle=’y-axis’ axis([ 0, 10, 0, 5 ]) xyouts, 2,25, ’hello’ text(2,25,’hello’) Axis labels and titles Insert text title(’title’) xlabel(’x-axis’) ylabel(’y-axis’) 10 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 7.1.2 Log plots Desc. logarithmic y-axis logarithmic x-axis logarithmic x and y axes 7.1.3 IDL plot, x,y, /YLOG or plot_io, x,y plot, x,y, /XLOG or plot_oi, x,y plot_oo, x,y Python semilogy(a) semilogx(a) loglog(a) matlab/Octave semilogy(a) semilogx(a) loglog(a) IDL Python matlab/Octave fill(t,s,’b’, t,c,’g’, alpha=0.2) fill(t,s,’b’, t,c,’g’) Octave: % fill has a bug? Python matlab/Octave f = inline(’sin(x/3) - cos(x/5)’) Filled plots and bar plots Desc. Filled plot 7.1.4 Functions IDL x 3 f (x) = sin ● ● ● ●● ●●● ● ● ● ● ● ● 0.5 ● ● ● ●● ●●● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ●● ●●●● ● ● ● ● f (x) −0.5 ● ● ● ● ● ● ● ● ● ● ● ● ● ● −1.0 ● ● ● ● ● ● ● ● ● 0.0 ● ● ● ● ● ● ● ● x 5 − cos 1.0 Desc. Defining functions ● ● ● ● ● ● ● ● ● −1.5 ● ● ● ● ● ● ● ● ● −2.0 ● 0 Plot a function for given range 7.2 Desc. x = arrayrange(0,40,.5) y = sin(x/3) - cos(x/5) plot(x,y, ’o’) ezplot(f,[0,40]) fplot(’sin(x/3) - cos(x/5)’,[0,40]) Octave: % no ezplot Python theta = arange(0,2*pi,0.001) r = sin(2*theta) matlab/Octave theta = 0:.001:2*pi; r = sin(2*theta); 10 20 30 x Polar plots IDL ρ(θ) = sin(2θ) 90 135 45 180 0 225 315 270 polar(theta, rho) polar(theta, rho) ●●●● ● 40 11 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net Histogram plots Desc. 7.4 7.4.1 IDL plot, histogram(randomn(5,1000)) Python matlab/Octave hist(randn(1000,1)) hist(randn(1000,1), -4:4) plot(sort(a)) IDL Python matlab/Octave 3d data Contour and image plots Desc. 0.0 2 6 0. 0.6 0.8 0.8 -0.6 -0.2 -0.4 0 0.2 1 0.4 7.3 1.0 -1 -0.2 -2 Contour plot contour, z -2 -1 0 1 2 -2 -1 0 1 2 levels, colls = contour(Z, V, contour(z) origin=’lower’, extent=(-3,3,-3,3)) clabel(colls, levels, inline=1, fmt=’%1.1f’, fontsize=10) 2 1 0 -1 -2 contour, z, nlevels=7, /fill contourf(Z, V, contour, z, nlevels=7, /overplot, /downhill cmap=cm.gray, origin=’lower’, extent=(-3,3,-3,3)) contourf(z); colormap(gray) Plot image data tv, z loadct,0 image(z) colormap(gray) im = imshow(Z, interpolation=’bilinear’, origin=’lower’, extent=(-3,3,-3,3)) 0.0 2 6 0. 0.6 0.8 0.8 -0.6 -0.2 -0.4 0 0.2 1 0.4 Filled contour plot 1.0 -1 -0.2 -2 -2 Image with contours Direction field vectors # imshow() and contour() as above quiver() quiver() -1 0 1 2 12 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 7.4.2 Perspective plots of surfaces over the x-y plane Desc. IDL Python matlab/Octave n=arrayrange(-2,2,.1) [x,y] = meshgrid(n,n) z = x*power(math.e,-x**2-y**2) n=-2:.1:2; [x,y] = meshgrid(n,n); z=x.*exp(-x.^2-y.^2); 2 −y 2 f (x, y) = xe−x 0.4 0.2 z 0.0 2 −0.2 1 −0.4 −2 y 0 −1 0 −1 x 1 2 Mesh plot surface, z −2 mesh(z) 0.4 0.2 z 0.0 2 −0.2 1 −0.4 −2 y 0 −1 0 −1 x 1 2 Surface plot 7.4.3 −2 surf(x,y,z) or surfl(x,y,z) Octave: % no surfl() shade_surf, z loadct,3 Scatter (cloud) plots Desc. IDL Python matlab/Octave ’icc-gamut.csv’ 80 60 40 20 0 -20 -40 -60 -80 100 90 80 70 60 80 50 60 40 40 20 30 0 20 -20 10 -40 d scatter plot -60 0 plot3(x,y,z,’k+’) 13 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 7.5 Save plot to a graphics file Desc. PostScript IDL set_plot,’PS’ device, file=’foo.eps’, /land plot x,y device,/close & set_plot,’win’ PDF SVG (vector graphics for www) PNG (raster graphics) 8 8.1 Python savefig(’foo.eps’) savefig(’foo.pdf’) savefig(’foo.svg’) savefig(’foo.png’) matlab/Octave plot(1:10) print -depsc2 foo.eps Octave: gset output "foo.eps" gset terminal postscript eps plot(1:10) print -dpng foo.png Data analysis Set membership operators Desc. Create sets Python a = array([1,2,2,5,2]) b = array([2,3,4]) a = set([1,2,2,5,2]) b = set([2,3,4]) unique1d(a) unique(a) set(a) matlab/Octave a = [ 1 2 2 5 2 ]; b = [ 2 3 4 ]; Set union union1d(a,b) a.union(b) union(a,b) Set intersection intersect1d(a) a.intersection(b) intersect(a,b) Set difference setdiff1d(a,b) a.difference(b) setdiff(a,b) Set exclusion setxor1d(a,b) a.symmetric_difference(b) 2 in a setmember1d(2,a) contains(a,2) setxor(a,b) Set unique True for set member IDL unique(a) ismember(2,a) 1 2 5 14 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 8.2 Statistics Desc. Average IDL mean(a) Python a.mean(axis=0) mean(a [,axis=0]) median(a) or median(a [,axis=0]) a.std(axis=0) or std(a [,axis=0]) a.var(axis=0) or var(a) correlate(x,y) or corrcoef(x,y) cov(x,y) Median Standard deviation Variance Correlation coefficient Covariance median(a) stddev(a) variance(a) correlate(x,y) median(a) std(a) var(a) corr(x,y) cov(x,y) Linear least squares y = ax + b Python (a,b) = polyfit(x,y,1) plot(x,y,’o’, x,a*x+b,’-’) linalg.lstsq(x,y) matlab/Octave z = polyval(polyfit(x,y,1),x) plot(x,y,’o’, x,z ,’-’) a = x\y Polynomial fit polyfit(x,y,3) polyfit(x,y,3) Python poly() roots() matlab/Octave 8.3 Interpolation and regression Desc. Straight line fit 8.4 8.4.1 IDL poly_fit(x,y,1) Non-linear methods Polynomials, root finding Desc. Polynomial Find zeros of polynomial Find a zero near x = 1 IDL roots([1 -1 -1]) f = inline(’1/x - (x-1)’) fzero(f,1) solve(’1/x = x-1’) polyval(array([1,2,1,2]),arange(1,11))polyval([1 2 1 2],1:10) Solve symbolic equations Evaluate polynomial 8.4.2 Differential equations Desc. Discrete difference function and approximate derivative Solve differential equations 8.5 IDL Python diff(x, n=1, axis=0) matlab/Octave diff(a) IDL fft(a) fft(a),/inverse convol() Python fft(a) or ifft(a) or convolve(x,y) matlab/Octave fft(a) ifft(a) Python matlab/Octave factor() Fourier analysis Desc. Fast fourier transform Inverse fourier transform Linear convolution 9 matlab/Octave mean(a) Symbolic algebra; calculus Desc. Factorization IDL x2 − x − 1 = 0 1 − (x − 1) f (x) = x 1 x =x−1 15 MATLAB commands in numerical Python Vidar Bronken Gundersen /mathesaurus.sf.net 10 Programming Desc. Script file extension Comment symbol (rest of line) IDL .idlbatch ; Python .py # Import library functions from pylab import * Eval string="a=234" eval(string) 10.1 Loops Desc. for-statement Multiline for statements 10.2 Python for i in range(1,6): print(i) for i in range(1,6): print(i) print(i*2) matlab/Octave for i=1:5; disp(i); end for i=1:5 disp(i) disp(i*2) end IDL if 1 gt 0 then a=100 if 1 gt 0 then a=100 else a=0 a>0?a:0 Python if 1>0: a=100 matlab/Octave if 1>0 a=100; end if 1>0 a=100; else a=0; end IDL Python a > 0?a : 0 Debugging Desc. Most recent evaluated expression List variables loaded into memory Clear variable x from memory Print 10.4 IDL for k=1,5 do print,k for k=1,5 do begin $ print, i &$ print, i*2 &$ end Conditionals Desc. if-statement if-else-statement Ternary operator (if?true:false) 10.3 matlab/Octave .m % Octave: % or # % must be in MATLABPATH Octave: % must be in LOADPATH string=’a=234’; eval(string) print a matlab/Octave ans whos or who clear x or clear [all] disp(a) Python os.listdir(".") grep.grep("*.py") os.getcwd() os.chdir(’foo’) os.system(’notepad’) os.popen(’notepad’) matlab/Octave dir or ls what pwd cd foo !notepad Octave: system("notepad") help print, a Working directory and OS Desc. List files in directory List script files in directory Displays the current working directory Change working directory Invoke a System Command IDL dir sd cd,’foo or sd,’foo spawn,’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. 16