NumPy For MATLAB Users
NumPy For MATLAB Users
8/27/12 6:51 AM
Python
Description
doc
help -i % browse with Info
help()
help
help help
or doc
doc
help plot
help splines
help(plot)
or doc
splines
or ?plot
help(pylab)
demo
Python
Description
help
which plot
help(plot)
MATLAB/Octave
Python
Description
octave -q
ipython -pylab
Start session
Auto completion
Run code from file
Command history
Save command history
End session
lookfor plot
Using interactively
TAB
or M-?
TAB
foo(.m)
execfile('foo.py')
history
hist -n
or quit
CTRL-D
CTRL-Z # windows
sys.exit()
or run
foo.py
Operators
MATLAB/Octave
help -
Python
Description
Arithmetic operators
http://mathesaurus.sourceforge.net/matlab-numpy.html
Page 1 of 16
8/27/12 6:51 AM
MATLAB/Octave
Python
Description
a=1; b=2;
a=1; b=1
a + b
a + b
a - b
a -
a * b
a *
a / b
a /
a .^ b
a ** b
or add(a,b)
b or subtract(a,b)
b or multiply(a,b)
b or divide(a,b)
Addition
Subtraction
Multiplication
Division
Power, $a^b$
power(a,b)
pow(a,b)
rem(a,b)
a % b
remainder(a,b)
fmod(a,b)
a+=1
a+=b
Remainder
or add(a,b,a)
factorial(a)
Relational operators
MATLAB/Octave
Python
a == b
a == b
a < b
a > b
a <= b
a >= b
a ~= b
Description
or equal(a,b)
< b or less(a,b)
> b or greater(a,b)
<= b or less_equal(a,b)
>= b or greater_equal(a,b)
!= b or not_equal(a,b)
Equal
Less than
Greater than
Less than or equal
Greater than or equal
Not Equal
Logical operators
MATLAB/Octave
Python
Description
a && b
a and b
a || b
a or b
or and(a,b)
b or or(a,b)
a & b
a |
xor(a, b)
~a
~a
or not(a)
or !a
or a and
logical_or(a,b) or a or b
logical_and(a,b)
logical_xor(a,b)
logical_not(a)
any(a)
all(a)
or not
Page 2 of 16
8/27/12 6:51 AM
MATLAB/Octave
Python
Description
sqrt(a)
math.sqrt(a)
Square root
log(a)
math.log(a)
log10(a)
math.log10(a)
log2(a)
math.log(a, 2)
exp(a)
math.exp(a)
MATLAB/Octave
Python
Description
round(a)
around(a)
ceil(a)
ceil(a)
floor(a)
floor(a)
fix(a)
fix(a)
Round off
or math.round(a)
Round
Round up
Round down
Round towards zero
Mathematical constants
MATLAB/Octave
Python
Description
pi
math.pi
exp(1)
math.e
$\pi=3.141592$
$e=2.718281$
or math.exp(1)
Python
Description
NaN
nan
Inf
inf
minus_zero
Not a Number
Infinity, $\infty$
Infinity, $+\infty$
Infinity, $-\infty$
Plus zero, $+0$
Minus zero, $-0$
MATLAB/Octave
Python
Description
z = 1j
z = 3+4i
z = 3+4j
abs(z)
abs(3+4j)
real(z)
z.real
imag(z)
z.imag
Imaginary unit
A complex number, $3+4i$
Absolute value (modulus)
Real part
Imaginary part
Argument
plus_inf
minus_inf
plus_zero
Complex numbers
arg(z)
http://mathesaurus.sourceforge.net/matlab-numpy.html
or z
= complex(3,4)
Page 3 of 16
conj(z)
8/27/12 6:51 AM
z.conj(); z.conjugate()
Complex conjugate
Trigonometry
MATLAB/Octave
Python
Description
atan(a,b)
atan2(b,a)
Arctangent, $\arctan(b/a)$
Hypotenus; Euclidean distance
hypot(x,y)
Python
Description
rand(1,10)
random.random((10,))
Uniform distribution
random.uniform((10,))
2+5*rand(1,10)
random.uniform(2,7,(10,))
rand(6)
random.uniform(0,1,(6,6))
randn(1,10)
random.standard_normal((10,))
MATLAB/Octave
Python
Description
a=[2 3 4 5];
a=array([2,3,4,5])
adash=[2 3 4 5]';
array([2,3,4,5])[:,NewAxis]
Vectors
array([2,3,4,5]).reshape(-1,1)
r_[1:10,'c']
Sequences
MATLAB/Octave
Python
Description
1:10
arange(1,11, dtype=Float)
range(1,11)
0:9
arange(10.)
1:3:10
arange(1,11,3)
10:-1:1
arange(10,0,-1)
10:-3:1
arange(10,0,-3)
linspace(1,10,7)
linspace(1,10,7)
reverse(a)
a[::-1]
a(:) = 3
a.fill(3), a[:] = 3
http://mathesaurus.sourceforge.net/matlab-numpy.html
or
Page 4 of 16
8/27/12 6:51 AM
Concatenation (vectors)
MATLAB/Octave
Python
Description
[a a]
concatenate((a,a))
[1:4 a]
concatenate((range(1,5),a),
axis=1)
Repeating
MATLAB/Octave
Python
Description
[a a]
concatenate((a,a))
1 2 3, 1 2 3
1 1 1, 2 2 2, 3 3 3
1, 2 2, 3 3 3
or
a.repeat(a) or
a.repeat(3)
Python
Description
a(2:end)
a[1:]
a([1:9])
a(end)
a[-1]
a(end-1:end)
a[-2:]
Python
Description
max(a,b)
maximum(a,b)
max([a b])
concatenate((a,b)).max()
pairwise max
max of all values in two vectors
[v,i] = max(a)
v,i = a.max(0),a.argmax(0)
Vector multiplication
MATLAB/Octave
Python
Description
a.*a
a*a
dot(u,v)
dot(u,v)
MATLAB/Octave
Python
Description
a = [2 3;4 5]
a = array([[2,3],[4,5]])
Define a matrix
Matrices
Page 5 of 16
8/27/12 6:51 AM
MATLAB/Octave
Python
Description
[a ; b]
concatenate((a,b), axis=0)
vstack((a,b))
Bind rows
[a , b]
concatenate((a,b), axis=1)
Bind columns
hstack((a,b))
concatenate((a,b), axis=2)
dstack((a,b))
[a(:), b(:)]
[1:4 ; 1:4]
vstack((r_[1:5],r_[1:5]))
[1:4 ; 1:4]'
Array creation
MATLAB/Octave
Python
Description
zeros(3,5)
zeros((3,5),Float)
0 filled array
0 filled array of integers
1 filled array
Any number filled array
Identity matrix
Diagonal
Magic squares; Lo Shu
Empty array
zeros((3,5))
ones(3,5)
ones((3,5),Float)
ones(3,5)*9
eye(3)
identity(3)
diag([4 5 6])
diag((4,5,6))
magic(3)
a = empty((3,3))
Python
Description
reshape(1:6,3,2)';
arange(1,7).reshape(2,-1)
a.setshape(2,3)
reshape(1:6,2,3);
arange(1,7).reshape(-1,2).transpose()
a'(:)
a.flatten()
a(:)
a.flatten(1)
or
vech(a)
Python
Description
b = a
b = a.copy()
Copy of a
http://mathesaurus.sourceforge.net/matlab-numpy.html
Page 6 of 16
8/27/12 6:51 AM
Python
Description
a = [ 11 12 13 14 ...
21 22 23 24 ...
31 32 33 34 ]
a(2,3)
a[1,2]
a(1,:)
a[0,]
a(:,1)
a[:,0]
a.take([0,2]).take([0,3], axis=1)
a(2:end,:)
a[1:,]
a(end-1:end,:)
a[-2:,]
a(1:2:end,:)
a[::2,:]
a.diagonal(offset=0)
MATLAB/Octave
Python
Description
a(:,1) = 99
a[:,0] = 99
a[:,0] = array([99,98,97])
a(a>90) = 90;
(a>90).choose(a,90)
a.clip(min=None, max=90)
a[...,2]
a(:,[1 3 4])
a.take([0,2,3],axis=1)
Assignment
a.clip(min=2, max=5)
MATLAB/Octave
Python
Description
a'
a.conj().transpose()
Transpose
Non-conjugate transpose
Determinant
Inverse
Pseudo-inverse
Norms
Eigenvalues
Singular values
Cholesky factorization
Eigenvectors
Rank
a.'
or transpose(a)
a.transpose()
inv(a)
or
linalg.inv(a) or
pinv(a)
linalg.pinv(a)
norm(a)
norm(a)
eig(a)
linalg.eig(a)[0]
svd(a)
linalg.svd(a)
chol(a)
linalg.cholesky(a)
[v,l] = eig(a)
linalg.eig(a)[1]
rank(a)
rank(a)
det(a)
linalg.det(a)
http://mathesaurus.sourceforge.net/matlab-numpy.html
Page 7 of 16
8/27/12 6:51 AM
Sum
MATLAB/Octave
Python
Description
sum(a)
a.sum(axis=0)
sum(a')
a.sum(axis=1)
sum(sum(a))
a.sum()
a.cumsum(axis=0)
MATLAB/Octave
Python
Description
a = [ 4 3 2 ; 2 8 6 ; 1 4 7 ]
a = array([[4,3,2],[2,8,6],
[1,4,7]])
Example data
sort(a(:))
a.ravel().sort()
sort(a)
a.sort(axis=0)
sort(a')'
a.sort(axis=1)
sortrows(a,1)
a[a[:,0].argsort(),]
a.trace(offset=0)
cumsum(a)
Sorting
or
a.argsort(axis=1)
MATLAB/Octave
Python
Description
max(a)
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)
max-to-min range
or msort(a)
a.ravel().argsort()
a.argsort(axis=0)
max(a')
max(max(a))
[v i] = max(a)
max(b,c)
cummax(a)
Matrix manipulation
MATLAB/Octave
Python
Description
fliplr(a)
fliplr(a)
flipud(a)
or a[:,::-1]
flipud(a) or a[::-1,]
rot90(a)
rot90(a)
repmat(a,2,3)
kron(ones(2,3),a)
kron(ones((2,3)),a)
Flip left-right
Flip up-down
Rotate 90 degrees
Repeat matrix: [ a a a ; a a a ]
http://mathesaurus.sourceforge.net/matlab-numpy.html
Page 8 of 16
8/27/12 6:51 AM
triu(a)
triu(a)
Triangular, upper
tril(a)
tril(a)
Triangular, lower
Equivalents to "size"
MATLAB/Octave
Python
Description
size(a)
a.shape
length(a(:))
or a.getshape()
a.shape[1] or size(a, axis=1)
a.size or size(a[, axis=None])
ndims(a)
a.ndim
Matrix dimensions
Number of columns
Number of elements
Number of dimensions
Number of bytes used in memory
size(a,2)
or length(a)
a.nbytes
Python
a .* b
a * b
a * b
matrixmultiply(a,b)
kron(a,b)
Description
or multiply(a,b)
inner(a,b)
or
outer(a,b)
or
Elementwise operations
Matrix product (dot product)
Inner matrix vector multiplication
$a\cdot b'$
Outer product
Kronecker product
Matrix division, $b{\cdot}a^{-1}$
Left matrix division, $b^{-1}
{\cdot}a$ \newline (solve linear
equations)
Vector dot product
Cross product
kron(a,b)
a / b
a \ b
linalg.solve(a,b)
vdot(a,b)
cross(a,b)
Python
Description
find(a)
a.ravel().nonzero()
[i j] = find(a)
(i,j) = a.nonzero()
(i,j) = where(a!=0)
[i j v] = find(a)
v = a.compress((a!=0).flat)
v = extract(a!=0,a)
find(a>5.5)
(a>5.5).nonzero()
a.compress((a>5.5).flat)
a .* (a>5.5)
where(a>5.5,0,a)
a.put(2,indices)
http://mathesaurus.sourceforge.net/matlab-numpy.html
or a
* (a>5.5)
Condition, indices
Return values
Zero out elements above 5.5
Replace values
Page 9 of 16
8/27/12 6:51 AM
Multi-way arrays
MATLAB/Octave
Python
Description
a = cat(3, [1 2; 1 2],[3 4; 3
4]);
a = array([[[1,2],[1,2]], [[3,4],
[3,4]]])
a(1,:,:)
a[0,...]
Python
Description
f = load('data.txt')
f = fromfile("data.txt")
f = load("data.txt")
f = load('data.txt')
f = load("data.txt")
x = dlmread('data.csv', ';')
f = load('data.csv',
delimiter=';')
save -ascii data.txt f
save('data.csv', f, fmt='%.6f',
delimiter=';')
f.tofile(file='data.csv',
format='%.6f', sep=';')
f = fromfile(file='data.csv',
sep=';')
Plotting
Basic x-y plots
MATLAB/Octave
Python
Description
plot(a)
plot(a)
plot(x(:,1),x(:,2),'o')
plot(x[:,0],x[:,1],'o')
plot(x1,y1, x2,y2)
plot(x1,y1,'bo', x2,y2,'go')
plot(x1,y1)
hold on
plot(x2,y2)
plot(x1,y1,'o')
plot(x2,y2,'o')
show() # as normal
1d line plot
2d scatter plot
Two graphs in one plot
Overplotting: Add new plots to
current
subplot(211)
subplot(211)
plot(x,y,'ro-')
plot(x,y,'ro-')
subplots
Plotting symbols and color
Python
Description
grid on
grid()
axis equal
figure(figsize=(6,6))
axis('equal')
http://mathesaurus.sourceforge.net/matlab-numpy.html
Page 10 of 16
8/27/12 6:51 AM
replot
axis([ 0 10 0 5 ])
axis([ 0, 10, 0, 5 ])
title('title')
xlabel('x-axis')
ylabel('y-axis')
text(2,25,'hello')
Insert text
Log plots
MATLAB/Octave
Python
Description
semilogy(a)
semilogy(a)
semilogx(a)
semilogx(a)
loglog(a)
loglog(a)
logarithmic y-axis
logarithmic x-axis
logarithmic x and y axes
MATLAB/Octave
Python
Description
fill(t,s,'b', t,c,'g')
% fill has a bug?
fill(t,s,'b', t,c,'g',
alpha=0.2)
Filled plot
Functions
MATLAB/Octave
Python
Description
Defining functions
f = inline('sin(x/3) cos(x/5)')
ezplot(f,[0,40])
fplot('sin(x/3) - cos(x/5)',
x = arrayrange(0,40,.5)
y = sin(x/3) - cos(x/5)
[0,40])
% no ezplot
plot(x,y, 'o')
Polar plots
MATLAB/Octave
Python
theta = 0:.001:2*pi;
theta = arange(0,2*pi,0.001)
r = sin(2*theta);
r = sin(2*theta)
polar(theta, rho)
polar(theta, rho)
Description
Histogram plots
MATLAB/Octave
Python
Description
hist(randn(1000,1))
hist(randn(1000,1), -4:4)
http://mathesaurus.sourceforge.net/matlab-numpy.html
Page 11 of 16
8/27/12 6:51 AM
plot(sort(a))
3d data
Contour and image plots
MATLAB/Octave
Python
Description
contour(z)
Contour plot
origin='lower', extent=
(-3,3,-3,3))
clabel(colls, levels, inline=1,
fmt='%1.1f', fontsize=10)
contourf(z); colormap(gray)
contourf(Z, V,
cmap=cm.gray,
origin='lower',
extent=(-3,3,-3,3))
image(z)
im = imshow(Z,
colormap(gray)
interpolation='bilinear',
origin='lower',
extent=(-3,3,-3,3))
# imshow() and contour() as above
quiver()
quiver()
Python
n=-2:.1:2;
[x,y] = meshgrid(n,n);
z=x.*exp(-x.^2-y.^2);
n=arrayrange(-2,2,.1)
[x,y] = meshgrid(n,n)
z = x*power(math.e,-x**2-y**2)
Description
Mesh plot
Surface plot
mesh(z)
surf(x,y,z) or surfl(x,y,z)
% no surfl()
Python
Description
3d scatter plot
plot3(x,y,z,'k+')
Python
Description
plot(1:10)
print -depsc2 foo.eps
savefig('foo.eps')
PostScript
http://mathesaurus.sourceforge.net/matlab-numpy.html
Page 12 of 16
8/27/12 6:51 AM
savefig('foo.svg')
savefig('foo.png')
MATLAB/Octave
Python
Description
a = [ 1 2 2 5 2 ];
b = [ 2 3 4 ];
a
b
a
b
Create sets
unique(a)
unique1d(a)
unique(a)
Data analysis
Set membership operators
=
=
=
=
array([1,2,2,5,2])
array([2,3,4])
set([1,2,2,5,2])
set([2,3,4])
Set unique
set(a)
union(a,b)
union1d(a,b)
Set union
a.union(b)
intersect(a,b)
intersect1d(a)
Set intersection
a.intersection(b)
setdiff(a,b)
setdiff1d(a,b)
Set difference
a.difference(b)
setxor(a,b)
setxor1d(a,b)
Set exclusion
a.symmetric_difference(b)
ismember(2,a)
2 in a
setmember1d(2,a)
contains(a,2)
Statistics
MATLAB/Octave
Python
Description
mean(a)
a.mean(axis=0)
mean(a [,axis=0])
Average
median(a)
median(a)
corr(x,y)
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)
cov(x,y)
Median
Standard deviation
Variance
Correlation coefficient
Covariance
std(a)
var(a)
http://mathesaurus.sourceforge.net/matlab-numpy.html
Page 13 of 16
8/27/12 6:51 AM
Python
Description
z = polyval(polyfit(x,y,1),x)
plot(x,y,'o', x,z ,'-')
(a,b) = polyfit(x,y,1)
plot(x,y,'o', x,a*x+b,'-')
a = x\y
linalg.lstsq(x,y)
polyfit(x,y,3)
polyfit(x,y,3)
Non-linear methods
Polynomials, root finding
MATLAB/Octave
roots([1 -1 -1])
Python
Description
poly()
Polynomial
Find zeros of polynomial
Find a zero near $x = 1$
roots()
f = inline('1/x - (x-1)')
fzero(f,1)
solve('1/x = x-1')
polyval([1 2 1 2],1:10)
Differential equations
MATLAB/Octave
Python
Description
diff(a)
MATLAB/Octave
Python
Description
fft(a)
fft(a)
or
ifft(a) or
Fourier analysis
ifft(a)
convolve(x,y)
Python
Description
Factorization
factor()
Programming
MATLAB/Octave
Python
http://mathesaurus.sourceforge.net/matlab-numpy.html
Description
Page 14 of 16
8/27/12 6:51 AM
.m
.py
%
%
% must be in MATLABPATH
% must be in LOADPATH
string='a=234';
eval(string)
string="a=234"
eval(string)
Eval
MATLAB/Octave
Python
Description
for i=1:5
disp(i)
for i in range(1,6):
print(i)
for-statement
Multiline for statements
disp(i*2)
end
print(i*2)
or #
Loops
Conditionals
MATLAB/Octave
Python
Description
if 1>0: a=100
if-statement
if-else-statement
Python
Description
print a
Debugging
MATLAB/Octave
ans
or who
clear x or clear
whos
[all]
disp(a)
or ls
Python
Description
os.listdir(".")
what
grep.grep("*.py")
pwd
os.getcwd()
cd foo
os.chdir('foo')
!notepad
os.system('notepad')
system("notepad")
os.popen('notepad')
http://mathesaurus.sourceforge.net/matlab-numpy.html
Page 15 of 16
8/27/12 6:51 AM
http://mathesaurus.sourceforge.net/matlab-numpy.html
Page 16 of 16