Przeglądaj wersję html pliku:
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
1
MATLAB commands in numerical Python (NumPy)
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. The idea of this document (and the corresponding xml instance) is to provide a quick reference for switching from matlab to an open-source environment, such as Python, Scilab, Octave and Gnuplot, or R for numeric processing and data visualisation. Where Octave and Scilab commands are omitted, expect Matlab compatibility, and similarly where non given use the generic command. Time-stamp: --T:: vidar
1
Help
matlab/Octave doc Octave: help -i % browse with Info help help or doc doc help plot help splines or doc splines demo Python help() help help(plot) or ?plot help(pylab) R help.start() help() help(plot) or ?plot help(package=’splines’) demo() example(plot)
Desc. Browse help interactively Help on using help Help for a function Help for a toolbox/library package Demonstration examples Example using a function
1.1
Searching available documentation
matlab/Octave lookfor plot help which plot Python R help.search(’plot’) apropos(’plot’) library() find(plot) methods(plot)
Desc. Search help files Find objects by partial name List available packages Locate functions List available methods for a function
help(); modules [Numeric] help(plot)
1.2
Using interactively
matlab/Octave Octave: octave -q Octave: TAB or M-? foo(.m) Octave: history diary on [..] diary off exit or quit Python ipython -pylab TAB execfile(’foo.py’) or run foo.py hist -n CTRL-D CTRL-Z # windows sys.exit() R Rgui source(’foo.R’) history() savehistory(file=".Rhistory") q(save=’no’)
Desc. Start session Auto completion Run code from file Command history Save command history End session
2
Operators
matlab/Octave help Python R help(Syntax)
Desc. Help on operator syntax
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 ..).
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
2
2.1
Arithmetic operators
matlab/Octave a=1; b=2; a + b a - b a * b a / b a .^ b 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) a+=b or add(a,b,a) factorial(a) R a<-1; b<-2 a + b a - b a * b a / b a ^ b
Desc. Assignment; defining a number Addition Subtraction Multiplication Division Power, ab
Remainder
rem(a,b)
a %% b
Integer division In place operation to save array creation overhead Factorial, n!
a %/% b Octave: a+=1 factorial(a)
2.2
Relational operators
matlab/Octave a == b a < b a > b a <= b a >= b a ~= 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) R a == b a < b a > b a <= b a >= b a != b
Desc. Equal Less than Greater than Less than or equal Greater than or equal Not Equal
2.3
Logical operators
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 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 R a && b a || b a & b a | b xor(a, b) !a
Desc. Short-circuit logical AND Short-circuit logical OR Element-wise logical AND Element-wise logical OR Logical EXCLUSIVE OR Logical NOT True if any element is nonzero True if all elements are nonzero
2.4
root and logarithm
matlab/Octave sqrt(a) log(a) log10(a) log2(a) exp(a) Python math.sqrt(a) math.log(a) math.log10(a) math.log(a, 2) math.exp(a) R sqrt(a) log(a) log10(a) log2(a) exp(a) √ a ln a = loge a log10 a log2 a ea
Desc. Square root Logarithm, base e (natural) Logarithm, base Logarithm, base (binary) Exponential function
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
3
2.5
Round off
matlab/Octave round(a) ceil(a) floor(a) fix(a) Python around(a) or math.round(a) ceil(a) floor(a) fix(a) R round(a) ceil(a) floor(a)
Desc. Round Round up Round down Round towards zero
2.6
Mathematical constants
matlab/Octave pi exp(1) Python math.pi math.e or math.exp(1) R pi exp(1)
Desc. π = 3.141592 e = 2.718281
2.6.1
Missing values; IEEE-754 floating point status flags
matlab/Octave NaN Inf Python nan inf plus_inf minus_inf plus_zero minus_zero R
Desc. Not a Number Infinity, ∞ Infinity, +∞ Infinity, −∞ Plus zero, +0 Minus zero, −0
2.7
Complex numbers
matlab/Octave i z = 3+4i abs(z) real(z) imag(z) arg(z) conj(z) Python z = 1j z = 3+4j or z = complex(3,4) abs(3+4j) z.real z.imag z.conj(); z.conjugate() R 1i z <- 3+4i abs(3+4i) or Mod(3+4i) Re(3+4i) Im(3+4i) Arg(3+4i) Conj(3+4i) i= √ −1
Desc. Imaginary unit A complex number, 3 + 4i Absolute value (modulus) Real part Imaginary part Argument Complex conjugate
2.8
Trigonometry
matlab/Octave atan(a,b) Python atan2(b,a) hypot(x,y) R atan2(b,a) x2 + y 2
Desc. Arctangent, arctan(b/a) Hypotenus; Euclidean distance
2.9
Generate random numbers
matlab/Octave rand(1,10) Python random.random((10,)) random.uniform((10,)) random.uniform(2,7,(10,)) random.uniform(0,1,(6,6)) random.standard_normal((10,)) R runif(10)
Desc. Uniform distribution
Uniform: Numbers between and Uniform: , array Normal distribution
2+5*rand(1,10) rand(6) randn(1,10)
runif(10, min=2, max=7) matrix(runif(36),6) rnorm(10)
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
4
3
Vectors
matlab/Octave a=[2 3 4 5]; adash=[2 3 4 5]’; 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’] R a <- c(2,3,4,5) adash <- t(c(2,3,4,5))
Desc. Row vector, 1 × n-matrix Column vector, m × 1-matrix
3.1
Sequences
matlab/Octave 1:10 0:9 1:3:10 10:-1:1 10:-3:1 linspace(1,10,7) reverse(a) a(:) = 3 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 R seq(10) or 1:10 seq(0,length=10) seq(1,10,by=3) seq(10,1) or 10:1 seq(from=10,to=1,by=-3) seq(1,10,length=7) rev(a)
Desc. ,,, ... , .,.,., ... ,. ,,, ,,, ... , ,,, Linearly spaced vector of n= points Reverse Set all values to same scalar value
3.2
Concatenation (vectors)
matlab/Octave [a a] [1:4 a] Python concatenate((a,a)) concatenate((range(1,5),a), axis=1) R c(a,a) c(1:4,a)
Desc. Concatenate two vectors
3.3
Repeating
matlab/Octave [a a] Python concatenate((a,a)) a.repeat(3) or a.repeat(a) or R rep(a,times=2) rep(a,each=3) rep(a,a)
Desc. , , , , ,
3.4
Miss those elements out
matlab/Octave a(2:end) a([1:9]) a(end) a(end-1:end) Python a[1:] R a[-1] a[-10] a[-seq(1,50,3)]
Desc. miss the first element miss the tenth element miss ,,, ... last element last two elements
a[-1] a[-2:]
3.5
Maximum and minimum
matlab/Octave max(a,b) max([a b]) [v,i] = max(a) Python maximum(a,b) concatenate((a,b)).max() v,i = a.max(0),a.argmax(0) R pmax(a,b) max(a,b) v <- max(a) ; i <- which.max(a)
Desc. pairwise max max of all values in two vectors
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
5
3.6
Vector multiplication
matlab/Octave a.*a dot(u,v) Python a*a dot(u,v) R a*a
Desc. Multiply two vectors Vector dot product, u · v
4
Matrices
matlab/Octave a = [2 3;4 5] Python a = array([[2,3],[4,5]]) R rbind(c(2,3),c(4,5)) array(c(2,3,4,5), dim=c(2,2)) 2 4 3 5
Desc. Define a matrix
4.1
Concatenation (matrices); rbind and cbind
matlab/Octave [a ; b] [a , b] Python R concatenate((a,b), axis=0) rbind(a,b) vstack((a,b)) concatenate((a,b), axis=1) cbind(a,b) hstack((a,b)) concatenate((a,b), axis=2) dstack((a,b)) concatenate((a,b), axis=None) concatenate((r_[1:5],r_[1:5])).reshape(2,-1) rbind(1:4,1:4) vstack((r_[1:5],r_[1:5])) cbind(1:4,1:4)
Desc. Bind rows Bind columns Bind slices (three-way arrays) Concatenate matrices into one vector Bind rows (from vectors) Bind columns (from vectors)
[a(:), b(:)] [1:4 ; 1:4] [1:4 ; 1:4]’
4.2
Desc.
Array creation
matlab/Octave zeros(3,5) Python zeros((3,5),Float) zeros((3,5)) ones(3,5) ones((3,5),Float) matrix(1,3,5) or array(1,c(3,5)) 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 R matrix(0,3,5) or array(0,c(3,5)) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
filled array filled array of integers filled array
Any number filled array
ones(3,5)*9
matrix(9,3,5) or array(9,c(3,5))
Identity matrix
eye(3)
identity(3)
diag(1,3)
Diagonal
diag([4 5 6])
diag((4,5,6))
diag(c(4,5,6))
Magic squares; Lo Shu Empty array
magic(3) a = empty((3,3))
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
6
4.3
Desc.
Reshape and flatten matrices
matlab/Octave reshape(1:6,3,2)’; reshape(1:6,2,3); a’(:) a(:) vech(a) Python arange(1,7).reshape(2,-1) a.setshape(2,3) R matrix(1:6,nrow=3,byrow=T) 1 4 1 2 1 1 2 5 3 4 2 4 3 6 5 6 3 2 4 5 5 3 6 6
Reshaping (rows first) Reshaping (columns first) Flatten to vector (by rows, like comics) Flatten to vector (by columns) Flatten upper triangle (by columns)
arange(1,7).reshape(-1,2).transpose() matrix(1:6,nrow=2) array(1:6,c(2,3)) as.vector(t(a)) a.flatten() or a.flatten(1) as.vector(a) a[row(a) <= col(a)]
4.4
Shared data (slicing)
matlab/Octave b = a Python b = a.copy() R b = a
Desc. Copy of a
4.5
Desc.
Indexing and accessing elements (Python: slicing)
matlab/Octave a = [ 11 12 13 14 ... 21 22 23 24 ... 31 32 33 34 ] a(2,3) a(1,:) a(:,1) a([1 3],[1 4]); a(2:end,:) a(end-1:end,:) a(1:2:end,:) Python a = array([[ 11, 12, 13, 14 ], [ 21, 22, 23, 24 ], [ 31, 32, 33, 34 ]]) a[1,2] a[0,] a[:,0] a.take([0,2]).take([0,3], axis=1) a[1:,] a[-2:,] a[::2,:] a[...,2] a[-2,-3] a(:,[1 3 4]) a.take([0,2,3],axis=1) a.diagonal(offset=0) a[,-2] a11 a31 a11 a21 a31 a11 a13 a33 a13 a23 a33 a22 a14 a34 a14 a24 a34 a33 a[-1,] R a <- rbind(c(11, 12, 13, 14), c(21, 22, 23, 24), c(31, 32, 33, 34)) a[2,3] a[1,] a[,1] a11 a21 a31 a23 a11 a11 a21 a31 a11 a31 a21 a31 a21 a31 a11 a31 a12 a22 a32 a13 a23 a33 a14 a24 a34
Input is a , array
Element , (row,col) First row First column Array as indices All, except first row Last two rows Strides: Every other row Third in last dimension (axis) All, except row,column (,) Remove one column Diagonal
a12
a13
a14
a14 a34 a22 a32 a22 a32 a12 a32 a23 a33 a23 a33 a13 a33 a24 a34 a24 a34 a14 a34
a44
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
7
4.6
Desc.
Assignment
matlab/Octave a(:,1) = 99 a(:,1) = [99 98 97]’ a(a>90) = 90; 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) R a[,1] <- 99 a[,1] <- c(99,98,97) a[a>90] <- 90
Clipping: Replace all elements over
Clip upper and lower values
4.7
Transpose and inverse
matlab/Octave a’ a.’ or transpose(a) det(a) inv(a) pinv(a) norm(a) eig(a) svd(a) chol(a) [v,l] = eig(a) rank(a) Python a.conj().transpose() a.transpose() linalg.det(a) or linalg.inv(a) or linalg.pinv(a) norm(a) linalg.eig(a)[0] linalg.svd(a) linalg.cholesky(a) linalg.eig(a)[1] rank(a) R t(a)
Desc. Transpose Non-conjugate transpose Determinant Inverse Pseudo-inverse Norms Eigenvalues Singular values Cholesky factorization Eigenvectors Rank
det(a) solve(a) ginv(a) eigen(a)$values svd(a)$d
eigen(a)$vectors rank(a)
4.8
Sum
matlab/Octave sum(a) sum(a’) sum(sum(a)) cumsum(a) Python a.sum(axis=0) a.sum(axis=1) a.sum() a.trace(offset=0) a.cumsum(axis=0) R apply(a,2,sum) apply(a,1,sum) sum(a) apply(a,2,cumsum)
Desc. Sum of each column Sum of each row Sum of all elements Sum along diagonal Cumulative sum (columns)
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
8
4.9
Desc.
Sorting
matlab/Octave a = [ 4 3 2 ; 2 8 6 ; 1 4 7 ] Python a = array([[4,3,2],[2,8,6],[1,4,7]]) R 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
Example data
Flat and sorted
sort(a(:))
a.ravel().sort() or
t(sort(a))
Sort each column
sort(a)
a.sort(axis=0) or msort(a)
apply(a,2,sort)
Sort each row
sort(a’)’
a.sort(axis=1)
t(apply(a,1,sort))
Sort rows (by first row) Sort, return indices Sort each column, return indices Sort each row, return indices
sortrows(a,1)
a[a[:,0].argsort(),] a.ravel().argsort() a.argsort(axis=0) a.argsort(axis=1) order(a)
4.10
Maximum and minimum
matlab/Octave max(a) max(a’) max(max(a)) [v i] = max(a) max(b,c) cummax(a) Python a.max(0) or amax(a [,axis=0]) a.max(1) or amax(a, axis=1) a.max() or maximum(b,c) a.ptp(); a.ptp(0) R apply(a,2,max) apply(a,1,max) max(a) i <- apply(a,1,which.max) pmax(b,c) apply(a,2,cummax)
Desc. max in each column max in each row max in array return indices, i pairwise max max-to-min range
4.11
Matrix manipulation
matlab/Octave fliplr(a) flipud(a) rot90(a) repmat(a,2,3) Octave: kron(ones(2,3),a) triu(a) tril(a) Python fliplr(a) or a[:,::-1] flipud(a) or a[::-1,] rot90(a) kron(ones((2,3)),a) triu(a) tril(a) R a[,4:1] a[3:1,] kronecker(matrix(1,2,3),a) a[lower.tri(a)] <- 0 a[upper.tri(a)] <- 0
Desc. Flip left-right Flip up-down Rotate degrees Repeat matrix: [ a a a ; a a a ] Triangular, upper Triangular, lower
4.12
Equivalents to ”size”
matlab/Octave size(a) size(a,2) or length(a) length(a(:)) ndims(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 R dim(a) ncol(a) prod(dim(a)) object.size(a)
Desc. Matrix dimensions Number of columns Number of elements Number of dimensions Number of bytes used in memory
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
9
4.13
Desc.
Matrix- and elementwise- multiplication
matlab/Octave a .* b a * b Python a * b or multiply(a,b) matrixmultiply(a,b) inner(a,b) or R a * b a %*% b 1 9 7 15 5 11 1 2 3 4 10 14 1 3 3 9 5 16 10 22 11 25 2 3 4 4 6 8 6 9 12 8 12 16 14 20 2 2 4 4 6 8 6 4 8 12 12 16
Elementwise operations Matrix product (dot product) Inner matrix vector multiplication a · b
Outer product
outer(a,b) or
outer(a,b) or a %o% b
Cross product
crossprod(a,b) or t(a) %*% b
Kronecker product Matrix division, b·a−1 Left matrix division, b−1 ·a (solve linear equations) Vector dot product Cross product
kron(a,b) a / b a \ b
kron(a,b)
kronecker(a,b)
linalg.solve(a,b) vdot(a,b) cross(a,b)
solve(a,b)
Ax = b
4.14
Find; conditional indexing
matlab/Octave find(a) [i j] = find(a) Python a.ravel().nonzero() (i,j) = a.nonzero() (i,j) = where(a!=0) v = a.compress((a!=0).flat) v = extract(a!=0,a) (a>5.5).nonzero() a.compress((a>5.5).flat) a .* (a>5.5) where(a>5.5,0,a) or a * (a>5.5) a.put(2,indices) R which(a != 0) which(a != 0, arr.ind=T)
Desc. Non-zero elements, indices Non-zero elements, array indices
Vector of non-zero values
[i j v] = find(a)
ij <- which(a != 0, arr.ind=T); v <- a[ij]
Condition, indices Return values Zero out elements above . Replace values
find(a>5.5)
which(a>5.5) ij <- which(a>5.5, arr.ind=T); v <- a[ij]
5
Multi-way arrays
matlab/Octave a = cat(3, [1 2; 1 2],[3 4; 3 4]); a(1,:,:) Python R a = array([[[1,2],[1,2]], [[3,4],[3,4]]]) a[0,...]
Desc. Define a -way array
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
10
6
File input and output
matlab/Octave f = load(’data.txt’) f = load(’data.txt’) x = dlmread(’data.csv’, ’;’) save -ascii data.txt f Python R f = fromfile("data.txt") f <- read.table("data.txt") f = load("data.txt") f = load("data.txt") f <- read.table("data.txt") f = load(’data.csv’, delimiter=’;’) f <- read.table(file="data.csv", sep=";") save(’data.csv’, f, fmt=’%.6f’, delimiter=’;’) write(f,file="data.txt") f.tofile(file=’data.csv’, format=’%.6f’, sep=’;’) f = fromfile(file=’data.csv’, sep=’;’)
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)
7
7.1
Plotting
Basic x-y plots
matlab/Octave Python R
4 3
Desc.
2
1
0
-1
-2
-3
-4
0
20
40
60
80
100
d line plot
plot(a)
plot(a)
plot(a, type="l")
4.5
4.0
3.5
3.0
2.5
2.0 4.0
4.5
5.0
5.5
6.0
6.5
7.0
7.5
8.0
d scatter plot
plot(x(:,1),x(:,2),’o’)
plot(x[:,0],x[:,1],’o’)
plot(x[,1],x[,2])
7 6
5
4
3
2
1 4.0
4.5
5.0
5.5
6.0
6.5
7.0
7.5
8.0
Two graphs in one plot Overplotting: Add new plots to current
subplots Plotting symbols and color
plot(x1,y1, x2,y2) plot(x1,y1) hold on plot(x2,y2) subplot(211) plot(x,y,’ro-’)
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) matplot(x2,y2,add=T)
plot(x,y,type="b",col="red")
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
11
7.1.1
Axes and titles
matlab/Octave grid on axis equal Octave: axis(’equal’) replot axis([ 0 10 0 5 ]) title(’title’) xlabel(’x-axis’) ylabel(’y-axis’) Python grid() figure(figsize=(6,6)) R grid() plot(c(1:10,10:1), asp=1)
Desc. Turn on grid lines : aspect ratio
Set axes manually Axis labels and titles
axis([ 0, 10, 0, 5 ])
plot(x,y, xlim=c(0,10), ylim=c(0,5)) plot(1:10, main="title", xlab="x-axis", ylab="y-axis")
Insert text
text(2,25,’hello’)
7.1.2
Log plots
matlab/Octave semilogy(a) semilogx(a) loglog(a) Python semilogy(a) semilogx(a) loglog(a) R plot(x,y, log="y") plot(x,y, log="x") plot(x,y, log="xy")
Desc. logarithmic y-axis logarithmic x-axis logarithmic x and y axes
7.1.3
Desc.
Filled plots and bar plots
matlab/Octave Python R
Filled plot
fill(t,s,’b’, t,c,’g’) Octave: % fill has a bug?
fill(t,s,’b’, t,c,’g’, alpha=0.2)
plot(t,s, type="n", xlab="", ylab="") polygon(t,s, col="lightblue") polygon(t,c, col="lightgreen") stem(x[,3])
5 6 7 8 9 10 5 71 033 00113345567889 0133566677788 32674
Stem-and-Leaf plot
7.1.4
Functions
matlab/Octave f = inline(’sin(x/3) - cos(x/5)’) Python R f <- function(x) sin(x/3) - cos(x/5) f (x) = sin
1.0
Desc. Defining functions
x 3
− cos
q q q q q q q qq qqq q q q q q q q
x 5
q q q q q q q q q q q q q q q q q q q q q q q q qqqq q q q q q q q q q
0.5
q q q q q q q
q
qq
qqq
q
q
q q q q q q q q q q q q q q qq q q q q
0.0
qqqq
f (x)
q
−0.5
q q q
−1.0
q q
−2.0
−1.5
0
10
20 x
30
40
Plot a function for given range
ezplot(f,[0,40]) fplot(’sin(x/3) - cos(x/5)’,[0,40]) Octave: % no ezplot
x = arrayrange(0,40,.5) y = sin(x/3) - cos(x/5) plot(x,y, ’o’)
plot(f, xlim=c(0,40), type=’p’)
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
12
7.2
Desc.
Polar plots
matlab/Octave theta = 0:.001:2*pi; r = sin(2*theta); Python theta = arange(0,2*pi,0.001) r = sin(2*theta) R ρ(θ) = sin(2θ)
90
135
45
180
0
225
315
270
polar(theta, rho)
polar(theta, rho)
7.3
Desc.
Histogram plots
matlab/Octave hist(randn(1000,1)) hist(randn(1000,1), -4:4) plot(sort(a)) Python R hist(rnorm(1000)) hist(rnorm(1000), breaks= -4:4) hist(rnorm(1000), breaks=c(seq(-5,0,0.25), seq(0.5,5,0.5)), freq=F) plot(apply(a,1,sort),type="l")
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
13
7.4
7.4.1
Desc.
3d data
Contour and image plots
matlab/Octave Python R
2
0.0
1
0.4
0.2
-0.2 -0.4
0.8
0.
6
0.6
-0.6
0
0.8
1.0
-1
-0.2
-2
-2
-1
0
1
2
Contour plot
contour(z)
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
-2
-1
0
1
2
Filled contour plot
contourf(z); colormap(gray)
contourf(Z, V, cmap=cm.gray, origin=’lower’, extent=(-3,3,-3,3))
filled.contour(x,y,z, nlevels=7, color=gray.colors)
Plot image data
image(z) colormap(gray)
im = imshow(Z, interpolation=’bilinear’, origin=’lower’, extent=(-3,3,-3,3))
image(z, col=gray.colors(256))
2
0.0
1
0.4
0.2
-0.2 -0.4
0.8
0.
6
0.6
-0.6
0
0.8
1.0
-1
-0.2
-2
-2
-1
0
1
2
Image with contours Direction field vectors
quiver()
# imshow() and contour() as above quiver()
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
14
7.4.2
Desc.
Perspective plots of surfaces over the x-y plane
matlab/Octave n=-2:.1:2; [x,y] = meshgrid(n,n); z=x.*exp(-x.^2-y.^2); Python n=arrayrange(-2,2,.1) [x,y] = meshgrid(n,n) z = x*power(math.e,-x**2-y**2) R f <- function(x,y) x*exp(-x^2-y^2) n <- seq(-2,2, length=40) z <- outer(n,n,f) f (x, y) = xe−x
2 −y 2
0.4
0.2 0.0 2 −0.2 1 −0.4 −2 −1 0 −1 1 2 −2 0
x
Mesh plot
mesh(z)
persp(x,y,z, theta=30, phi=30, expand=0.6, ticktype=’detailed’)
0.4 0.2 0.0 −0.2 1 −0.4 −2 −1 0 −1 1 −2
y
2 0
y
z
z
x
2
Surface plot
surf(x,y,z) or surfl(x,y,z) Octave: % no surfl()
persp(x,y,z, theta=30, phi=30, expand=0.6, col=’lightblue’, shade=0.75, ltheta=120, ticktype=’detailed’)
7.4.3
Desc.
Scatter (cloud) plots
matlab/Octave Python R
’icc-gamut.csv’
80 60 40 20 0 -20 -40 -60 -80 70 80 60 40 20 0 -20 -40 10 -60 0 20 30 40 50 60
100 90 80
d scatter plot
plot3(x,y,z,’k+’)
cloud(z~x*y)
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
15
7.5
Save plot to a graphics file
matlab/Octave plot(1:10) print -depsc2 foo.eps Octave: gset output "foo.eps" gset terminal postscript eps plot(1:10) Python savefig(’foo.eps’) R postscript(file="foo.eps") plot(1:10) dev.off()
Desc. PostScript
PDF SVG (vector graphics for www) PNG (raster graphics)
print -dpng foo.png
savefig(’foo.pdf’) savefig(’foo.svg’) savefig(’foo.png’)
pdf(file=’foo.pdf’) devSVG(file=’foo.svg’) png(filename = "Rplot%03d.png"
8
8.1
Data analysis
Set membership operators
matlab/Octave a = [ 1 2 2 5 2 ]; b = [ 2 3 4 ]; 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) R a <- c(1,2,2,5,2) b <- c(2,3,4)
Desc. Create sets
Set unique
unique(a)
unique(a)
1
2
5
Set union
union(a,b)
union1d(a,b) a.union(b)
union(a,b)
Set intersection
intersect(a,b)
intersect1d(a) a.intersection(b)
intersect(a,b)
Set difference
setdiff(a,b)
setdiff1d(a,b) a.difference(b)
setdiff(a,b)
Set exclusion True for set member
setxor(a,b) ismember(2,a)
setxor1d(a,b) a.symmetric_difference(b) 2 in a setmember1d(2,a) contains(a,2)
setdiff(union(a,b),intersect(a,b)) is.element(2,a) or 2 %in% a
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
16
8.2
Statistics
matlab/Octave mean(a) median(a) std(a) var(a) corr(x,y) cov(x,y) 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) R apply(a,2,mean) apply(a,2,median) apply(a,2,sd) apply(a,2,var) cor(x,y) cov(x,y)
Desc. Average Median Standard deviation Variance Correlation coefficient Covariance
8.3
Interpolation and regression
matlab/Octave z = polyval(polyfit(x,y,1),x) plot(x,y,’o’, x,z ,’-’) a = x\y polyfit(x,y,3) Python (a,b) = polyfit(x,y,1) plot(x,y,’o’, x,a*x+b,’-’) linalg.lstsq(x,y) polyfit(x,y,3) R z <- lm(y~x) plot(x,y) abline(z) solve(a,b)
Desc. Straight line fit
Linear least squares y = ax + b Polynomial fit
8.4
8.4.1
Non-linear methods
Polynomials, root finding
matlab/Octave roots([1 -1 -1]) f = inline(’1/x - (x-1)’) fzero(f,1) solve(’1/x = x-1’) polyval([1 2 1 2],1:10) Python poly() roots() R polyroot(c(1,-1,-1)) x2 − x − 1 = 0 1 f (x) = x − (x − 1)
1 x
Desc. Polynomial Find zeros of polynomial Find a zero near x = 1 Solve symbolic equations Evaluate polynomial
=x−1
polyval(array([1,2,1,2]),arange(1,11))
8.4.2
Differential equations
matlab/Octave diff(a) Python diff(x, n=1, axis=0) R
Desc. Discrete difference function and approximate derivative Solve differential equations
8.5
Fourier analysis
matlab/Octave fft(a) ifft(a) Python fft(a) or ifft(a) or convolve(x,y) R fft(a) fft(a, inverse=TRUE)
Desc. Fast fourier transform Inverse fourier transform Linear convolution
9
Symbolic algebra; calculus
matlab/Octave factor() Python R
Desc. Factorization
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
17
10
Programming
matlab/Octave .m % Octave: % or # % must be in MATLABPATH Octave: % must be in LOADPATH string=’a=234’; eval(string) Python .py # from pylab import * string="a=234" eval(string) R .R # library(RSvgDevice) string <- "a <- 234" eval(parse(text=string))
Desc. Script file extension Comment symbol (rest of line) Import library functions Eval
10.1
Loops
matlab/Octave for i=1:5; disp(i); end for i=1:5 disp(i) disp(i*2) end Python for i in range(1,6): print(i) for i in range(1,6): print(i) print(i*2) R for(i in 1:5) print(i) for(i in 1:5) { print(i) print(i*2) }
Desc. for-statement Multiline for statements
10.2
Conditionals
matlab/Octave if 1>0 a=100; end if 1>0 a=100; else a=0; end Python if 1>0: a=100 R if (1>0) a <- 100 ifelse(a>0,a,0) a > 0?a : 0
Desc. if-statement if-else-statement Ternary operator (if?true:false)
10.3
Debugging
matlab/Octave ans whos or who clear x or clear [all] disp(a) Python R .Last.value objects() rm(x) print(a)
Desc. Most recent evaluated expression List variables loaded into memory Clear variable x from memory Print
print a
10.4
Working directory and OS
matlab/Octave dir or ls what pwd cd foo !notepad Octave: system("notepad") Python os.listdir(".") grep.grep("*.py") os.getcwd() os.chdir(’foo’) os.system(’notepad’) os.popen(’notepad’) R list.files() or dir() list.files(pattern="\.r$") getwd() setwd(’foo’) system("notepad")
Desc. List files in directory List script files in directory Displays the current working directory Change working directory Invoke a System Command
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/; R .., http://www.r-project.org/; Octave .., http://www.octave.org/; Scilab ., http://www.scilab.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.
MATLAB commands in numerical Python (ang)
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
1
MATLAB commands in numerical Python (NumPy)
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. The idea of this document (and the corresponding xml instance) is to provide a quick reference for switching from matlab to an open-source environment, such as Python, Scilab, Octave and Gnuplot, or R for numeric processing and data visualisation. Where Octave and Scilab commands are omitted, expect Matlab compatibility, and similarly where non given use the generic command. Time-stamp: --T:: vidar
1
Help
matlab/Octave doc Octave: help -i % browse with Info help help or doc doc help plot help splines or doc splines demo Python help() help help(plot) or ?plot help(pylab) R help.start() help() help(plot) or ?plot help(package=’splines’) demo() example(plot)
Desc. Browse help interactively Help on using help Help for a function Help for a toolbox/library package Demonstration examples Example using a function
1.1
Searching available documentation
matlab/Octave lookfor plot help which plot Python R help.search(’plot’) apropos(’plot’) library() find(plot) methods(plot)
Desc. Search help files Find objects by partial name List available packages Locate functions List available methods for a function
help(); modules [Numeric] help(plot)
1.2
Using interactively
matlab/Octave Octave: octave -q Octave: TAB or M-? foo(.m) Octave: history diary on [..] diary off exit or quit Python ipython -pylab TAB execfile(’foo.py’) or run foo.py hist -n CTRL-D CTRL-Z # windows sys.exit() R Rgui source(’foo.R’) history() savehistory(file=".Rhistory") q(save=’no’)
Desc. Start session Auto completion Run code from file Command history Save command history End session
2
Operators
matlab/Octave help Python R help(Syntax)
Desc. Help on operator syntax
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 ..).
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
2
2.1
Arithmetic operators
matlab/Octave a=1; b=2; a + b a - b a * b a / b a .^ b 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) a+=b or add(a,b,a) factorial(a) R a<-1; b<-2 a + b a - b a * b a / b a ^ b
Desc. Assignment; defining a number Addition Subtraction Multiplication Division Power, ab
Remainder
rem(a,b)
a %% b
Integer division In place operation to save array creation overhead Factorial, n!
a %/% b Octave: a+=1 factorial(a)
2.2
Relational operators
matlab/Octave a == b a < b a > b a <= b a >= b a ~= 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) R a == b a < b a > b a <= b a >= b a != b
Desc. Equal Less than Greater than Less than or equal Greater than or equal Not Equal
2.3
Logical operators
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 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 R a && b a || b a & b a | b xor(a, b) !a
Desc. Short-circuit logical AND Short-circuit logical OR Element-wise logical AND Element-wise logical OR Logical EXCLUSIVE OR Logical NOT True if any element is nonzero True if all elements are nonzero
2.4
root and logarithm
matlab/Octave sqrt(a) log(a) log10(a) log2(a) exp(a) Python math.sqrt(a) math.log(a) math.log10(a) math.log(a, 2) math.exp(a) R sqrt(a) log(a) log10(a) log2(a) exp(a) √ a ln a = loge a log10 a log2 a ea
Desc. Square root Logarithm, base e (natural) Logarithm, base Logarithm, base (binary) Exponential function
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
3
2.5
Round off
matlab/Octave round(a) ceil(a) floor(a) fix(a) Python around(a) or math.round(a) ceil(a) floor(a) fix(a) R round(a) ceil(a) floor(a)
Desc. Round Round up Round down Round towards zero
2.6
Mathematical constants
matlab/Octave pi exp(1) Python math.pi math.e or math.exp(1) R pi exp(1)
Desc. π = 3.141592 e = 2.718281
2.6.1
Missing values; IEEE-754 floating point status flags
matlab/Octave NaN Inf Python nan inf plus_inf minus_inf plus_zero minus_zero R
Desc. Not a Number Infinity, ∞ Infinity, +∞ Infinity, −∞ Plus zero, +0 Minus zero, −0
2.7
Complex numbers
matlab/Octave i z = 3+4i abs(z) real(z) imag(z) arg(z) conj(z) Python z = 1j z = 3+4j or z = complex(3,4) abs(3+4j) z.real z.imag z.conj(); z.conjugate() R 1i z <- 3+4i abs(3+4i) or Mod(3+4i) Re(3+4i) Im(3+4i) Arg(3+4i) Conj(3+4i) i= √ −1
Desc. Imaginary unit A complex number, 3 + 4i Absolute value (modulus) Real part Imaginary part Argument Complex conjugate
2.8
Trigonometry
matlab/Octave atan(a,b) Python atan2(b,a) hypot(x,y) R atan2(b,a) x2 + y 2
Desc. Arctangent, arctan(b/a) Hypotenus; Euclidean distance
2.9
Generate random numbers
matlab/Octave rand(1,10) Python random.random((10,)) random.uniform((10,)) random.uniform(2,7,(10,)) random.uniform(0,1,(6,6)) random.standard_normal((10,)) R runif(10)
Desc. Uniform distribution
Uniform: Numbers between and Uniform: , array Normal distribution
2+5*rand(1,10) rand(6) randn(1,10)
runif(10, min=2, max=7) matrix(runif(36),6) rnorm(10)
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
4
3
Vectors
matlab/Octave a=[2 3 4 5]; adash=[2 3 4 5]’; 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’] R a <- c(2,3,4,5) adash <- t(c(2,3,4,5))
Desc. Row vector, 1 × n-matrix Column vector, m × 1-matrix
3.1
Sequences
matlab/Octave 1:10 0:9 1:3:10 10:-1:1 10:-3:1 linspace(1,10,7) reverse(a) a(:) = 3 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 R seq(10) or 1:10 seq(0,length=10) seq(1,10,by=3) seq(10,1) or 10:1 seq(from=10,to=1,by=-3) seq(1,10,length=7) rev(a)
Desc. ,,, ... , .,.,., ... ,. ,,, ,,, ... , ,,, Linearly spaced vector of n= points Reverse Set all values to same scalar value
3.2
Concatenation (vectors)
matlab/Octave [a a] [1:4 a] Python concatenate((a,a)) concatenate((range(1,5),a), axis=1) R c(a,a) c(1:4,a)
Desc. Concatenate two vectors
3.3
Repeating
matlab/Octave [a a] Python concatenate((a,a)) a.repeat(3) or a.repeat(a) or R rep(a,times=2) rep(a,each=3) rep(a,a)
Desc. , , , , ,
3.4
Miss those elements out
matlab/Octave a(2:end) a([1:9]) a(end) a(end-1:end) Python a[1:] R a[-1] a[-10] a[-seq(1,50,3)]
Desc. miss the first element miss the tenth element miss ,,, ... last element last two elements
a[-1] a[-2:]
3.5
Maximum and minimum
matlab/Octave max(a,b) max([a b]) [v,i] = max(a) Python maximum(a,b) concatenate((a,b)).max() v,i = a.max(0),a.argmax(0) R pmax(a,b) max(a,b) v <- max(a) ; i <- which.max(a)
Desc. pairwise max max of all values in two vectors
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
5
3.6
Vector multiplication
matlab/Octave a.*a dot(u,v) Python a*a dot(u,v) R a*a
Desc. Multiply two vectors Vector dot product, u · v
4
Matrices
matlab/Octave a = [2 3;4 5] Python a = array([[2,3],[4,5]]) R rbind(c(2,3),c(4,5)) array(c(2,3,4,5), dim=c(2,2)) 2 4 3 5
Desc. Define a matrix
4.1
Concatenation (matrices); rbind and cbind
matlab/Octave [a ; b] [a , b] Python R concatenate((a,b), axis=0) rbind(a,b) vstack((a,b)) concatenate((a,b), axis=1) cbind(a,b) hstack((a,b)) concatenate((a,b), axis=2) dstack((a,b)) concatenate((a,b), axis=None) concatenate((r_[1:5],r_[1:5])).reshape(2,-1) rbind(1:4,1:4) vstack((r_[1:5],r_[1:5])) cbind(1:4,1:4)
Desc. Bind rows Bind columns Bind slices (three-way arrays) Concatenate matrices into one vector Bind rows (from vectors) Bind columns (from vectors)
[a(:), b(:)] [1:4 ; 1:4] [1:4 ; 1:4]’
4.2
Desc.
Array creation
matlab/Octave zeros(3,5) Python zeros((3,5),Float) zeros((3,5)) ones(3,5) ones((3,5),Float) matrix(1,3,5) or array(1,c(3,5)) 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 R matrix(0,3,5) or array(0,c(3,5)) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
filled array filled array of integers filled array
Any number filled array
ones(3,5)*9
matrix(9,3,5) or array(9,c(3,5))
Identity matrix
eye(3)
identity(3)
diag(1,3)
Diagonal
diag([4 5 6])
diag((4,5,6))
diag(c(4,5,6))
Magic squares; Lo Shu Empty array
magic(3) a = empty((3,3))
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
6
4.3
Desc.
Reshape and flatten matrices
matlab/Octave reshape(1:6,3,2)’; reshape(1:6,2,3); a’(:) a(:) vech(a) Python arange(1,7).reshape(2,-1) a.setshape(2,3) R matrix(1:6,nrow=3,byrow=T) 1 4 1 2 1 1 2 5 3 4 2 4 3 6 5 6 3 2 4 5 5 3 6 6
Reshaping (rows first) Reshaping (columns first) Flatten to vector (by rows, like comics) Flatten to vector (by columns) Flatten upper triangle (by columns)
arange(1,7).reshape(-1,2).transpose() matrix(1:6,nrow=2) array(1:6,c(2,3)) as.vector(t(a)) a.flatten() or a.flatten(1) as.vector(a) a[row(a) <= col(a)]
4.4
Shared data (slicing)
matlab/Octave b = a Python b = a.copy() R b = a
Desc. Copy of a
4.5
Desc.
Indexing and accessing elements (Python: slicing)
matlab/Octave a = [ 11 12 13 14 ... 21 22 23 24 ... 31 32 33 34 ] a(2,3) a(1,:) a(:,1) a([1 3],[1 4]); a(2:end,:) a(end-1:end,:) a(1:2:end,:) Python a = array([[ 11, 12, 13, 14 ], [ 21, 22, 23, 24 ], [ 31, 32, 33, 34 ]]) a[1,2] a[0,] a[:,0] a.take([0,2]).take([0,3], axis=1) a[1:,] a[-2:,] a[::2,:] a[...,2] a[-2,-3] a(:,[1 3 4]) a.take([0,2,3],axis=1) a.diagonal(offset=0) a[,-2] a11 a31 a11 a21 a31 a11 a13 a33 a13 a23 a33 a22 a14 a34 a14 a24 a34 a33 a[-1,] R a <- rbind(c(11, 12, 13, 14), c(21, 22, 23, 24), c(31, 32, 33, 34)) a[2,3] a[1,] a[,1] a11 a21 a31 a23 a11 a11 a21 a31 a11 a31 a21 a31 a21 a31 a11 a31 a12 a22 a32 a13 a23 a33 a14 a24 a34
Input is a , array
Element , (row,col) First row First column Array as indices All, except first row Last two rows Strides: Every other row Third in last dimension (axis) All, except row,column (,) Remove one column Diagonal
a12
a13
a14
a14 a34 a22 a32 a22 a32 a12 a32 a23 a33 a23 a33 a13 a33 a24 a34 a24 a34 a14 a34
a44
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
7
4.6
Desc.
Assignment
matlab/Octave a(:,1) = 99 a(:,1) = [99 98 97]’ a(a>90) = 90; 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) R a[,1] <- 99 a[,1] <- c(99,98,97) a[a>90] <- 90
Clipping: Replace all elements over
Clip upper and lower values
4.7
Transpose and inverse
matlab/Octave a’ a.’ or transpose(a) det(a) inv(a) pinv(a) norm(a) eig(a) svd(a) chol(a) [v,l] = eig(a) rank(a) Python a.conj().transpose() a.transpose() linalg.det(a) or linalg.inv(a) or linalg.pinv(a) norm(a) linalg.eig(a)[0] linalg.svd(a) linalg.cholesky(a) linalg.eig(a)[1] rank(a) R t(a)
Desc. Transpose Non-conjugate transpose Determinant Inverse Pseudo-inverse Norms Eigenvalues Singular values Cholesky factorization Eigenvectors Rank
det(a) solve(a) ginv(a) eigen(a)$values svd(a)$d
eigen(a)$vectors rank(a)
4.8
Sum
matlab/Octave sum(a) sum(a’) sum(sum(a)) cumsum(a) Python a.sum(axis=0) a.sum(axis=1) a.sum() a.trace(offset=0) a.cumsum(axis=0) R apply(a,2,sum) apply(a,1,sum) sum(a) apply(a,2,cumsum)
Desc. Sum of each column Sum of each row Sum of all elements Sum along diagonal Cumulative sum (columns)
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
8
4.9
Desc.
Sorting
matlab/Octave a = [ 4 3 2 ; 2 8 6 ; 1 4 7 ] Python a = array([[4,3,2],[2,8,6],[1,4,7]]) R 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
Example data
Flat and sorted
sort(a(:))
a.ravel().sort() or
t(sort(a))
Sort each column
sort(a)
a.sort(axis=0) or msort(a)
apply(a,2,sort)
Sort each row
sort(a’)’
a.sort(axis=1)
t(apply(a,1,sort))
Sort rows (by first row) Sort, return indices Sort each column, return indices Sort each row, return indices
sortrows(a,1)
a[a[:,0].argsort(),] a.ravel().argsort() a.argsort(axis=0) a.argsort(axis=1) order(a)
4.10
Maximum and minimum
matlab/Octave max(a) max(a’) max(max(a)) [v i] = max(a) max(b,c) cummax(a) Python a.max(0) or amax(a [,axis=0]) a.max(1) or amax(a, axis=1) a.max() or maximum(b,c) a.ptp(); a.ptp(0) R apply(a,2,max) apply(a,1,max) max(a) i <- apply(a,1,which.max) pmax(b,c) apply(a,2,cummax)
Desc. max in each column max in each row max in array return indices, i pairwise max max-to-min range
4.11
Matrix manipulation
matlab/Octave fliplr(a) flipud(a) rot90(a) repmat(a,2,3) Octave: kron(ones(2,3),a) triu(a) tril(a) Python fliplr(a) or a[:,::-1] flipud(a) or a[::-1,] rot90(a) kron(ones((2,3)),a) triu(a) tril(a) R a[,4:1] a[3:1,] kronecker(matrix(1,2,3),a) a[lower.tri(a)] <- 0 a[upper.tri(a)] <- 0
Desc. Flip left-right Flip up-down Rotate degrees Repeat matrix: [ a a a ; a a a ] Triangular, upper Triangular, lower
4.12
Equivalents to ”size”
matlab/Octave size(a) size(a,2) or length(a) length(a(:)) ndims(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 R dim(a) ncol(a) prod(dim(a)) object.size(a)
Desc. Matrix dimensions Number of columns Number of elements Number of dimensions Number of bytes used in memory
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
9
4.13
Desc.
Matrix- and elementwise- multiplication
matlab/Octave a .* b a * b Python a * b or multiply(a,b) matrixmultiply(a,b) inner(a,b) or R a * b a %*% b 1 9 7 15 5 11 1 2 3 4 10 14 1 3 3 9 5 16 10 22 11 25 2 3 4 4 6 8 6 9 12 8 12 16 14 20 2 2 4 4 6 8 6 4 8 12 12 16
Elementwise operations Matrix product (dot product) Inner matrix vector multiplication a · b
Outer product
outer(a,b) or
outer(a,b) or a %o% b
Cross product
crossprod(a,b) or t(a) %*% b
Kronecker product Matrix division, b·a−1 Left matrix division, b−1 ·a (solve linear equations) Vector dot product Cross product
kron(a,b) a / b a \ b
kron(a,b)
kronecker(a,b)
linalg.solve(a,b) vdot(a,b) cross(a,b)
solve(a,b)
Ax = b
4.14
Find; conditional indexing
matlab/Octave find(a) [i j] = find(a) Python a.ravel().nonzero() (i,j) = a.nonzero() (i,j) = where(a!=0) v = a.compress((a!=0).flat) v = extract(a!=0,a) (a>5.5).nonzero() a.compress((a>5.5).flat) a .* (a>5.5) where(a>5.5,0,a) or a * (a>5.5) a.put(2,indices) R which(a != 0) which(a != 0, arr.ind=T)
Desc. Non-zero elements, indices Non-zero elements, array indices
Vector of non-zero values
[i j v] = find(a)
ij <- which(a != 0, arr.ind=T); v <- a[ij]
Condition, indices Return values Zero out elements above . Replace values
find(a>5.5)
which(a>5.5) ij <- which(a>5.5, arr.ind=T); v <- a[ij]
5
Multi-way arrays
matlab/Octave a = cat(3, [1 2; 1 2],[3 4; 3 4]); a(1,:,:) Python R a = array([[[1,2],[1,2]], [[3,4],[3,4]]]) a[0,...]
Desc. Define a -way array
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
10
6
File input and output
matlab/Octave f = load(’data.txt’) f = load(’data.txt’) x = dlmread(’data.csv’, ’;’) save -ascii data.txt f Python R f = fromfile("data.txt") f <- read.table("data.txt") f = load("data.txt") f = load("data.txt") f <- read.table("data.txt") f = load(’data.csv’, delimiter=’;’) f <- read.table(file="data.csv", sep=";") save(’data.csv’, f, fmt=’%.6f’, delimiter=’;’) write(f,file="data.txt") f.tofile(file=’data.csv’, format=’%.6f’, sep=’;’) f = fromfile(file=’data.csv’, sep=’;’)
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)
7
7.1
Plotting
Basic x-y plots
matlab/Octave Python R
4 3
Desc.
2
1
0
-1
-2
-3
-4
0
20
40
60
80
100
d line plot
plot(a)
plot(a)
plot(a, type="l")
4.5
4.0
3.5
3.0
2.5
2.0 4.0
4.5
5.0
5.5
6.0
6.5
7.0
7.5
8.0
d scatter plot
plot(x(:,1),x(:,2),’o’)
plot(x[:,0],x[:,1],’o’)
plot(x[,1],x[,2])
7 6
5
4
3
2
1 4.0
4.5
5.0
5.5
6.0
6.5
7.0
7.5
8.0
Two graphs in one plot Overplotting: Add new plots to current
subplots Plotting symbols and color
plot(x1,y1, x2,y2) plot(x1,y1) hold on plot(x2,y2) subplot(211) plot(x,y,’ro-’)
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) matplot(x2,y2,add=T)
plot(x,y,type="b",col="red")
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
11
7.1.1
Axes and titles
matlab/Octave grid on axis equal Octave: axis(’equal’) replot axis([ 0 10 0 5 ]) title(’title’) xlabel(’x-axis’) ylabel(’y-axis’) Python grid() figure(figsize=(6,6)) R grid() plot(c(1:10,10:1), asp=1)
Desc. Turn on grid lines : aspect ratio
Set axes manually Axis labels and titles
axis([ 0, 10, 0, 5 ])
plot(x,y, xlim=c(0,10), ylim=c(0,5)) plot(1:10, main="title", xlab="x-axis", ylab="y-axis")
Insert text
text(2,25,’hello’)
7.1.2
Log plots
matlab/Octave semilogy(a) semilogx(a) loglog(a) Python semilogy(a) semilogx(a) loglog(a) R plot(x,y, log="y") plot(x,y, log="x") plot(x,y, log="xy")
Desc. logarithmic y-axis logarithmic x-axis logarithmic x and y axes
7.1.3
Desc.
Filled plots and bar plots
matlab/Octave Python R
Filled plot
fill(t,s,’b’, t,c,’g’) Octave: % fill has a bug?
fill(t,s,’b’, t,c,’g’, alpha=0.2)
plot(t,s, type="n", xlab="", ylab="") polygon(t,s, col="lightblue") polygon(t,c, col="lightgreen") stem(x[,3])
5 6 7 8 9 10 5 71 033 00113345567889 0133566677788 32674
Stem-and-Leaf plot
7.1.4
Functions
matlab/Octave f = inline(’sin(x/3) - cos(x/5)’) Python R f <- function(x) sin(x/3) - cos(x/5) f (x) = sin
1.0
Desc. Defining functions
x 3
− cos
q q q q q q q qq qqq q q q q q q q
x 5
q q q q q q q q q q q q q q q q q q q q q q q q qqqq q q q q q q q q q
0.5
q q q q q q q
q
qqq
q
q
q q q q q q q q q q q q q q qq q q q q
0.0
qqqq
f (x)
q
−0.5
q q q
−1.0
q q
−2.0
−1.5
0
10
20 x
30
40
Plot a function for given range
ezplot(f,[0,40]) fplot(’sin(x/3) - cos(x/5)’,[0,40]) Octave: % no ezplot
x = arrayrange(0,40,.5) y = sin(x/3) - cos(x/5) plot(x,y, ’o’)
plot(f, xlim=c(0,40), type=’p’)
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
12
7.2
Desc.
Polar plots
matlab/Octave theta = 0:.001:2*pi; r = sin(2*theta); Python theta = arange(0,2*pi,0.001) r = sin(2*theta) R ρ(θ) = sin(2θ)
90
135
45
180
0
225
315
270
polar(theta, rho)
polar(theta, rho)
7.3
Desc.
Histogram plots
matlab/Octave hist(randn(1000,1)) hist(randn(1000,1), -4:4) plot(sort(a)) Python R hist(rnorm(1000)) hist(rnorm(1000), breaks= -4:4) hist(rnorm(1000), breaks=c(seq(-5,0,0.25), seq(0.5,5,0.5)), freq=F) plot(apply(a,1,sort),type="l")
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
13
7.4
7.4.1
Desc.
3d data
Contour and image plots
matlab/Octave Python R
2
0.0
1
0.4
0.2
-0.2 -0.4
0.8
0.
6
0.6
-0.6
0
0.8
1.0
-1
-0.2
-2
-2
-1
0
1
2
Contour plot
contour(z)
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
-2
-1
0
1
2
Filled contour plot
contourf(z); colormap(gray)
contourf(Z, V, cmap=cm.gray, origin=’lower’, extent=(-3,3,-3,3))
filled.contour(x,y,z, nlevels=7, color=gray.colors)
Plot image data
image(z) colormap(gray)
im = imshow(Z, interpolation=’bilinear’, origin=’lower’, extent=(-3,3,-3,3))
image(z, col=gray.colors(256))
2
0.0
1
0.4
0.2
-0.2 -0.4
0.8
0.
6
0.6
-0.6
0
0.8
1.0
-1
-0.2
-2
-2
-1
0
1
2
Image with contours Direction field vectors
quiver()
# imshow() and contour() as above quiver()
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
14
7.4.2
Desc.
Perspective plots of surfaces over the x-y plane
matlab/Octave n=-2:.1:2; [x,y] = meshgrid(n,n); z=x.*exp(-x.^2-y.^2); Python n=arrayrange(-2,2,.1) [x,y] = meshgrid(n,n) z = x*power(math.e,-x**2-y**2) R f <- function(x,y) x*exp(-x^2-y^2) n <- seq(-2,2, length=40) z <- outer(n,n,f) f (x, y) = xe−x
2 −y 2
0.4
0.2 0.0 2 −0.2 1 −0.4 −2 −1 0 −1 1 2 −2 0
x
Mesh plot
mesh(z)
persp(x,y,z, theta=30, phi=30, expand=0.6, ticktype=’detailed’)
0.4 0.2 0.0 −0.2 1 −0.4 −2 −1 0 −1 1 −2
y
2 0
y
z
z
x
2
Surface plot
surf(x,y,z) or surfl(x,y,z) Octave: % no surfl()
persp(x,y,z, theta=30, phi=30, expand=0.6, col=’lightblue’, shade=0.75, ltheta=120, ticktype=’detailed’)
7.4.3
Desc.
Scatter (cloud) plots
matlab/Octave Python R
’icc-gamut.csv’
80 60 40 20 0 -20 -40 -60 -80 70 80 60 40 20 0 -20 -40 10 -60 0 20 30 40 50 60
100 90 80
d scatter plot
plot3(x,y,z,’k+’)
cloud(z~x*y)
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
15
7.5
Save plot to a graphics file
matlab/Octave plot(1:10) print -depsc2 foo.eps Octave: gset output "foo.eps" gset terminal postscript eps plot(1:10) Python savefig(’foo.eps’) R postscript(file="foo.eps") plot(1:10) dev.off()
Desc. PostScript
PDF SVG (vector graphics for www) PNG (raster graphics)
print -dpng foo.png
savefig(’foo.pdf’) savefig(’foo.svg’) savefig(’foo.png’)
pdf(file=’foo.pdf’) devSVG(file=’foo.svg’) png(filename = "Rplot%03d.png"
8
8.1
Data analysis
Set membership operators
matlab/Octave a = [ 1 2 2 5 2 ]; b = [ 2 3 4 ]; 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) R a <- c(1,2,2,5,2) b <- c(2,3,4)
Desc. Create sets
Set unique
unique(a)
unique(a)
1
2
5
Set union
union(a,b)
union1d(a,b) a.union(b)
union(a,b)
Set intersection
intersect(a,b)
intersect1d(a) a.intersection(b)
intersect(a,b)
Set difference
setdiff(a,b)
setdiff1d(a,b) a.difference(b)
setdiff(a,b)
Set exclusion True for set member
setxor(a,b) ismember(2,a)
setxor1d(a,b) a.symmetric_difference(b) 2 in a setmember1d(2,a) contains(a,2)
setdiff(union(a,b),intersect(a,b)) is.element(2,a) or 2 %in% a
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
16
8.2
Statistics
matlab/Octave mean(a) median(a) std(a) var(a) corr(x,y) cov(x,y) 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) R apply(a,2,mean) apply(a,2,median) apply(a,2,sd) apply(a,2,var) cor(x,y) cov(x,y)
Desc. Average Median Standard deviation Variance Correlation coefficient Covariance
8.3
Interpolation and regression
matlab/Octave z = polyval(polyfit(x,y,1),x) plot(x,y,’o’, x,z ,’-’) a = x\y polyfit(x,y,3) Python (a,b) = polyfit(x,y,1) plot(x,y,’o’, x,a*x+b,’-’) linalg.lstsq(x,y) polyfit(x,y,3) R z <- lm(y~x) plot(x,y) abline(z) solve(a,b)
Desc. Straight line fit
Linear least squares y = ax + b Polynomial fit
8.4
8.4.1
Non-linear methods
Polynomials, root finding
matlab/Octave roots([1 -1 -1]) f = inline(’1/x - (x-1)’) fzero(f,1) solve(’1/x = x-1’) polyval([1 2 1 2],1:10) Python poly() roots() R polyroot(c(1,-1,-1)) x2 − x − 1 = 0 1 f (x) = x − (x − 1)
1 x
Desc. Polynomial Find zeros of polynomial Find a zero near x = 1 Solve symbolic equations Evaluate polynomial
=x−1
polyval(array([1,2,1,2]),arange(1,11))
8.4.2
Differential equations
matlab/Octave diff(a) Python diff(x, n=1, axis=0) R
Desc. Discrete difference function and approximate derivative Solve differential equations
8.5
Fourier analysis
matlab/Octave fft(a) ifft(a) Python fft(a) or ifft(a) or convolve(x,y) R fft(a) fft(a, inverse=TRUE)
Desc. Fast fourier transform Inverse fourier transform Linear convolution
9
Symbolic algebra; calculus
matlab/Octave factor() Python R
Desc. Factorization
MATLAB commands in numerical Python (NumPy) Vidar Bronken Gundersen /mathesaurus.sf.net
17
10
Programming
matlab/Octave .m % Octave: % or # % must be in MATLABPATH Octave: % must be in LOADPATH string=’a=234’; eval(string) Python .py # from pylab import * string="a=234" eval(string) R .R # library(RSvgDevice) string <- "a <- 234" eval(parse(text=string))
Desc. Script file extension Comment symbol (rest of line) Import library functions Eval
10.1
Loops
matlab/Octave for i=1:5; disp(i); end for i=1:5 disp(i) disp(i*2) end Python for i in range(1,6): print(i) for i in range(1,6): print(i) print(i*2) R for(i in 1:5) print(i) for(i in 1:5) { print(i) print(i*2) }
Desc. for-statement Multiline for statements
10.2
Conditionals
matlab/Octave if 1>0 a=100; end if 1>0 a=100; else a=0; end Python if 1>0: a=100 R if (1>0) a <- 100 ifelse(a>0,a,0) a > 0?a : 0
Desc. if-statement if-else-statement Ternary operator (if?true:false)
10.3
Debugging
matlab/Octave ans whos or who clear x or clear [all] disp(a) Python R .Last.value objects() rm(x) print(a)
Desc. Most recent evaluated expression List variables loaded into memory Clear variable x from memory Print
print a
10.4
Working directory and OS
matlab/Octave dir or ls what pwd cd foo !notepad Octave: system("notepad") Python os.listdir(".") grep.grep("*.py") os.getcwd() os.chdir(’foo’) os.system(’notepad’) os.popen(’notepad’) R list.files() or dir() list.files(pattern="\.r$") getwd() setwd(’foo’) system("notepad")
Desc. List files in directory List script files in directory Displays the current working directory Change working directory Invoke a System Command
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/; R .., http://www.r-project.org/; Octave .., http://www.octave.org/; Scilab ., http://www.scilab.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.