0% found this document useful (0 votes)
260 views

NumPy For MATLAB Users

MATLAB commands in Python

Uploaded by

vladadj_1603
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
260 views

NumPy For MATLAB Users

MATLAB commands in Python

Uploaded by

vladadj_1603
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

NumPy for MATLAB users Mathesaurus

8/27/12 6:51 AM

NumPy for MATLAB users


Help
MATLAB/Octave

Python

Description

doc
help -i % browse with Info

help()

Browse help interactively

help

Help on using help


Help for a function
Help for a toolbox/library package
Demonstration examples

help help

or doc

doc

help plot
help splines

help(plot)

or doc

splines

or ?plot

help(pylab)

demo

Searching available documentation


MATLAB/Octave

Python

Description

help

help(); modules [Numeric]

which plot

help(plot)

Search help files


List available packages
Locate functions

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

diary on [..] diary off


exit

or quit

CTRL-D
CTRL-Z # windows
sys.exit()

or run

foo.py

Operators
MATLAB/Octave
help -

Python

Description

Help on operator syntax

Arithmetic operators

http://mathesaurus.sourceforge.net/matlab-numpy.html

Page 1 of 16

NumPy for MATLAB users Mathesaurus

8/27/12 6:51 AM

MATLAB/Octave

Python

Description

a=1; b=2;

a=1; b=1

Assignment; defining a number

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)

In place operation to save array


creation overhead
Factorial, $n!$

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

Short-circuit logical AND


Short-circuit logical OR
Element-wise logical AND
Element-wise logical OR
Logical EXCLUSIVE OR
Logical NOT

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

True if any element is nonzero


True if all elements are nonzero

root and logarithm


http://mathesaurus.sourceforge.net/matlab-numpy.html

Page 2 of 16

NumPy for MATLAB users Mathesaurus

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)

Logarithm, base $e$ (natural)


Logarithm, base 10
Logarithm, base 2 (binary)
Exponential function

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)

Missing values; IEEE-754 floating point status flags


MATLAB/Octave

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

NumPy for MATLAB users Mathesaurus

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)

Generate random numbers


MATLAB/Octave

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,))

Uniform: Numbers between 2 and


7
Uniform: 6,6 array
Normal distribution

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]

Row vector, $1 \times n$-matrix


Column vector, $m \times 1$matrix

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)

1,2,3, ... ,10

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

0.0,1.0,2.0, ... ,9.0


1,4,7,10
10,9,8, ... ,1
10,7,4,1
Linearly spaced vector of n=7
points
Reverse
Set all values to same scalar value

http://mathesaurus.sourceforge.net/matlab-numpy.html

or

Page 4 of 16

NumPy for MATLAB users Mathesaurus

8/27/12 6:51 AM

Concatenation (vectors)
MATLAB/Octave

Python

Description

[a a]

concatenate((a,a))

Concatenate two vectors

[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)

Miss those elements out


MATLAB/Octave

Python

Description

a(2:end)

a[1:]

miss the first element


miss the tenth element
last element
last two elements

a([1:9])
a(end)

a[-1]

a(end-1:end)

a[-2:]

Maximum and minimum


MATLAB/Octave

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)

Multiply two vectors


Vector dot product, $u \cdot v$

MATLAB/Octave

Python

Description

a = [2 3;4 5]

a = array([[2,3],[4,5]])

Define a matrix

Matrices

Concatenation (matrices); rbind and cbind


http://mathesaurus.sourceforge.net/matlab-numpy.html

Page 5 of 16

NumPy for MATLAB users Mathesaurus

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))

Bind slices (three-way arrays)

concatenate((a,b), axis=2)
dstack((a,b))
[a(:), b(:)]
[1:4 ; 1:4]

Concatenate matrices into


one vector
concatenate((r_[1:5],r_[1:5])).reshape(2,-1) Bind rows (from vectors)
concatenate((a,b), axis=None)

vstack((r_[1:5],r_[1:5]))

Bind columns (from vectors)

[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))

Reshape and flatten matrices


MATLAB/Octave

Python

Description

reshape(1:6,3,2)';

arange(1,7).reshape(2,-1)

Reshaping (rows first)

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)

Reshaping (columns first)


Flatten to vector (by rows, like
comics)
Flatten to vector (by columns)
Flatten upper triangle (by
columns)

Shared data (slicing)


MATLAB/Octave

Python

Description

b = a

b = a.copy()

Copy of a

http://mathesaurus.sourceforge.net/matlab-numpy.html

Page 6 of 16

NumPy for MATLAB users Mathesaurus

8/27/12 6:51 AM

Indexing and accessing elements (Python: slicing)


MATLAB/Octave

Python

Description

a = [ 11 12 13 14 ...
21 22 23 24 ...

a = array([[ 11, 12, 13, 14 ],


[ 21, 22, 23, 24 ],

Input is a 3,4 array

31 32 33 34 ]

[ 31, 32, 33, 34 ]])

a(2,3)

a[1,2]

a(1,:)

a[0,]

a(:,1)

a[:,0]

a([1 3],[1 4]);

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)

Element 2,3 (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)
Remove one column
Diagonal

MATLAB/Octave

Python

Description

a(:,1) = 99

a[:,0] = 99

a(:,1) = [99 98 97]'

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)

Clipping: Replace all elements over


90
Clip upper and lower values

MATLAB/Octave

Python

Description

a'

a.conj().transpose()

Transpose
Non-conjugate transpose
Determinant
Inverse
Pseudo-inverse
Norms
Eigenvalues
Singular values
Cholesky factorization
Eigenvectors
Rank

Transpose and inverse

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

NumPy for MATLAB users Mathesaurus

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)

Sum of each column


Sum of each row
Sum of all elements
Sum along diagonal
Cumulative sum (columns)

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)

Flat and sorted


Sort each column
Sort each row
Sort rows (by first row)
Sort, return indices
Sort each column, return indices
Sort each row, return indices

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)

max in each column


max in each row
max in array
return indices, i
pairwise max

a.ptp(); a.ptp(0)

max-to-min range

or msort(a)

a.ravel().argsort()
a.argsort(axis=0)

Maximum and minimum

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

NumPy for MATLAB users Mathesaurus

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

Matrix- and elementwise- multiplication


MATLAB/Octave

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)

Find; conditional indexing


MATLAB/Octave

Python

Description

find(a)

a.ravel().nonzero()

[i j] = find(a)

(i,j) = a.nonzero()

Non-zero elements, indices


Non-zero elements, array indices

(i,j) = where(a!=0)
[i j v] = find(a)

v = a.compress((a!=0).flat)

Vector of non-zero values

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

NumPy for MATLAB users Mathesaurus

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]]])

Define a 3-way array

a(1,:,:)

a[0,...]

File input and output


MATLAB/Octave

Python

Description

f = load('data.txt')

f = fromfile("data.txt")
f = load("data.txt")

Reading from a file (2d)

f = load('data.txt')

f = load("data.txt")

x = dlmread('data.csv', ';')

f = load('data.csv',

Reading from a file (2d)


Reading fram a CSV file (2d)

delimiter=';')
save -ascii data.txt f

save('data.csv', f, fmt='%.6f',

Writing to a file (2d)

delimiter=';')
f.tofile(file='data.csv',

Writing to a file (1d)

format='%.6f', sep=';')
f = fromfile(file='data.csv',

Reading from a file (1d)

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

Axes and titles


MATLAB/Octave

Python

Description

grid on

grid()

axis equal

figure(figsize=(6,6))

Turn on grid lines


1:1 aspect ratio

axis('equal')

http://mathesaurus.sourceforge.net/matlab-numpy.html

Page 10 of 16

NumPy for MATLAB users Mathesaurus

8/27/12 6:51 AM

replot
axis([ 0 10 0 5 ])

axis([ 0, 10, 0, 5 ])

Set axes manually


Axis labels and titles

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

Filled plots and bar plots

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')

Plot a function for given range

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

NumPy for MATLAB users Mathesaurus

8/27/12 6:51 AM

plot(sort(a))

3d data
Contour and image plots
MATLAB/Octave

Python

Description

contour(z)

levels, colls = contour(Z, V,

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,

Filled contour plot

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()

Plot image data

Image with contours


Direction field vectors

Perspective plots of surfaces over the x-y plane


MATLAB/Octave

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()

Scatter (cloud) plots


MATLAB/Octave

Python

Description

3d scatter plot

plot3(x,y,z,'k+')

Save plot to a graphics file


MATLAB/Octave

Python

Description

plot(1:10)
print -depsc2 foo.eps

savefig('foo.eps')

PostScript

http://mathesaurus.sourceforge.net/matlab-numpy.html

Page 12 of 16

NumPy for MATLAB users Mathesaurus

8/27/12 6:51 AM

gset output "foo.eps"


gset terminal postscript eps
plot(1:10)
savefig('foo.pdf')

PDF

savefig('foo.svg')
savefig('foo.png')

SVG (vector graphics for www)


PNG (raster graphics)

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)

print -dpng foo.png

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

True for set member

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

NumPy for MATLAB users Mathesaurus

8/27/12 6:51 AM

Interpolation and regression


MATLAB/Octave

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,'-')

Straight line fit

a = x\y

linalg.lstsq(x,y)

polyfit(x,y,3)

polyfit(x,y,3)

Linear least squares $y = ax + b$


Polynomial fit

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)

Solve symbolic equations


polyval(array([1,2,1,2]),arange(1,11)) Evaluate polynomial

Differential equations
MATLAB/Octave

Python

Description

diff(a)

diff(x, n=1, axis=0)

Discrete difference function and


approximate derivative
Solve differential equations

MATLAB/Octave

Python

Description

fft(a)

fft(a)

or
ifft(a) or

Fast fourier transform


Inverse fourier transform
Linear convolution

Fourier analysis

ifft(a)

convolve(x,y)

Symbolic algebra; calculus


MATLAB/Octave

Python

Description

Factorization

factor()

Programming
MATLAB/Octave

Python

http://mathesaurus.sourceforge.net/matlab-numpy.html

Description
Page 14 of 16

NumPy for MATLAB users Mathesaurus

8/27/12 6:51 AM

.m

.py

Script file extension

%
%

Comment symbol (rest of line)

% must be in MATLABPATH
% must be in LOADPATH

from pylab import *

Import library functions

string='a=234';
eval(string)

string="a=234"
eval(string)

Eval

MATLAB/Octave

Python

Description

for i=1:5; disp(i); end

for i in range(1,6): print(i)

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; end

if 1>0: a=100

if-statement
if-else-statement

Python

Description

print a

Most recent evaluated expression


List variables loaded into memory
Clear variable $x$ from memory
Print

if 1>0 a=100; else a=0; end

Debugging
MATLAB/Octave
ans

or who
clear x or clear
whos

[all]

disp(a)

Working directory and OS


MATLAB/Octave
dir

or ls

Python

Description

os.listdir(".")

List files in directory


List script files in directory
Displays the current working
directory
Change working directory
Invoke a System Command

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

NumPy for MATLAB users Mathesaurus

8/27/12 6:51 AM

Time-stamp: "2007-11-09T16:46:36 vidar"


2006 Vidar Bronken Gundersen, /mathesaurus.sf.net
Permission is granted to copy, distribute and/or modify this document as long as the above attribution is retained.

http://mathesaurus.sourceforge.net/matlab-numpy.html

Page 16 of 16

You might also like