MATLAB commands in numerical Python

advertisement
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
MATLAB 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 to open-source mathematical
computation environments for computer algebra, numeric processing and data visualisation. Examples of well known systems are matlab, idl,
R, SPlus, with their open-source counterparts Octave, Scilab, FreeMat, Python (NumPy and matplotlib modules), and Gnuplot. Or cas tools
like Mathematica, Maple, MuPAD, with Axiom and Maxima as open alternatives.
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
Scilab
R
Python
gnuplot
idl
Axiom
Browse help interactively
doc
help -i % browse with Info
help
help.start()
help()
help or ?
?
)hd
matlab
R
Python
idl
Axiom
Help on using help
help help or doc doc
help()
help
?help
)help ?
matlab
R
Python
gnuplot
idl
Maxima
Maple
Mathematica
MuPAD
Help for a function
help plot
help(plot) or ?plot
help(plot) or ?plot
help plot or ?plot
?plot or man,’plot
describe(keyword)$
?keyword
?keyword
?keyword
matlab
R
Python
Help for a toolbox/library package
help splines or doc splines
help(package=’splines’)
help(pylab)
matlab
Scilab
R
idl
Demonstration examples
demo
demoplay();
demo()
demo
R
Maxima
Example using a function
example(plot)
example(factor);
1.1
Searching available documentation
matlab
R
Search help files
lookfor plot
help.search(’plot’)
R
Scilab
Axiom
Maxima
Maple
Mathematica
MuPAD
Find objects by partial name
apropos(’plot’)
apropos plot
)what operations pattern
describe(pattern)$
?keyword
?*pattern*
?*pattern*
 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
..); Wester, Michael (ed). Computer Algebra Systems: A Practical Guide (), available from
http://www.math.unm.edu/˜wester/cas review.html (accessed ..).
1
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
matlab
R
Python
List available packages
help
library()
help(); modules [Numeric]
matlab
Scilab
R
Python
Locate functions
which plot
whereis plot
find(plot)
help(plot)
R
List available methods for a function
methods(plot)
1.2
Using interactively
Octave
R
Python
idl
bc
gnuplot
Start session
octave -q
Rgui
ipython -pylab
idlde
bc -lq
pgnuplot
Octave
Scilab
Python
Auto completion
TAB or M-?
! // commands in history
TAB
matlab
Scilab
R
Python
gnuplot
idl
Maxima
Run code from file
foo(.m)
exec(’foo.sce’)
source(’foo.R’)
execfile(’foo.py’) or run foo.py
load ’foo.gp’
@"foo.idlbatch" or .run ’foo.pro’
batch("foo.mc")
Octave
Scilab
R
Python
idl
Axiom
Command history
history
gethistory
history()
hist -n
help,/rec
)history )show
matlab
Scilab
R
idl
Axiom
Save command history
diary on [..] diary off
diary(’session.txt’) [..] diary(0)
savehistory(file=".Rhistory")
journal,’IDLhistory’
)hist )write foo.input
matlab
R
Python
gnuplot
idl
Axiom
Maxima
Maple
Mathematica
MuPAD
Derive
reduce
bc
2
Operators
matlab
Scilab
R
2.1
End session
exit or quit
q(save=’no’)
CTRL-D
CTRL-Z # windows
sys.exit()
exit or quit
exit or CTRL-D
)quit
quit();
quit
Quit[]
quit
[Quit]
quit;
quit
Help on operator syntax
help help symbols
help(Syntax)
Arithmetic operators
matlab
R
Python
idl
bc
Assignment; defining a number
a=1; b=2;
a<-1; b<-2
a=1; b=1
a=1 & b=1
a=1; b=1
2
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
Generic
matlab
R
Python
gnuplot
idl
bc
Addition
a + b
a + b
a + b
a + b or add(a,b)
a + b
a + b
a + b
Generic
matlab
R
Python
gnuplot
idl
bc
Subtraction
a - b
a - b
a - b
a - b or subtract(a,b)
a - b
a - b
a - b
Generic
matlab
R
Python
gnuplot
idl
bc
Multiplication
a * b
a * b
a * b
a * b or multiply(a,b)
a * b
a * b
a * b
Generic
matlab
R
Python
gnuplot
idl
Division
a / b
a / b
a / b
a / b or divide(a,b)
a / b
a / b
matlab
R
Python
gnuplot
idl
Axiom
Maxima
bc
Power, ab
a .^ b
a ^ b
a ** b
power(a,b)
pow(a,b)
a ** b
a ^ b
a**b
a^b or a**b
a ^ b
gnuplot
idl
Axiom
Maxima
Maple
Mathematica
MuPAD
Derive
bc
Remainder
rem(a,b)
modulo(a,b)
a %% b
a % b
remainder(a,b)
fmod(a,b)
a % b
a MOD b
rem(a,b)
mod(a,b)
a mod b
Mod[a,b]
a mod b
MOD(a,b)
a % b
R
bc
Integer division
a %/% b
a / b
Octave
idl
bc
Increment, return new value
++a
++a or a+=1
++a
Octave
idl
bc
Increment, return old value
a++
a++
a++
Python
Octave
idl
bc
In place operation to save array creation overhead
a+=b or add(a,b,a)
a+=1
a+=1
a+=b
matlab
R
Axiom
Maxima
Maple
Factorial, n!
factorial(a)
factorial(a)
factorial(a)
a!
a!
matlab
Scilab
R
Python
3
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
2.2
Relational operators
Generic
matlab
R
Python
idl
bc
Equal
a == b
a == b
a == b
a == b or equal(a,b)
a eq b
a == b
Generic
matlab
R
Python
idl
bc
Less than
a < b
a < b
a < b
a < b or less(a,b)
a lt b
a < b
Generic
matlab
R
Python
idl
bc
Greater than
a > b
a > b
a > b
a > b or greater(a,b)
a gt b
a > b
Generic
matlab
R
Python
idl
bc
Less
a <=
a <=
a <=
a <=
a le
a <=
Generic
matlab
R
Python
idl
bc
Greater than or equal
a >= b
a >= b
a >= b
a >= b or greater_equal(a,b)
a ge b
a >= b
matlab
Scilab
R
Python
idl
bc
Not Equal
a ~= b
a ~= b or a <> b
a != b
a != b or not_equal(a,b)
a ne b
a != b
2.3
than or equal
b
b
b
b or less_equal(a,b)
b
b
Logical operators
matlab
Python
R
bc
Short-circuit logical AND
a && b
a and b
a && b
a && b
matlab
Python
R
bc
Short-circuit logical OR
a || b
a or b
a || b
a || b
matlab
R
Python
idl
Element-wise logical AND
a & b or and(a,b)
a & b
logical_and(a,b) or a and b
a and b
matlab
R
Python
idl
Element-wise logical OR
a | b or or(a,b)
a | b
logical_or(a,b) or a or b
a or b
matlab
R
Python
idl
Logical EXCLUSIVE OR
xor(a, b)
xor(a, b)
logical_xor(a,b)
a xor b
matlab
Octave
R
Python
idl
bc
Logical NOT
~a or not(a)
~a or !a
!a
logical_not(a) or not a
not a
!a
matlab
True if any element is nonzero
any(a)
4
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
matlab
Scilab
2.4
True if all elements are nonzero
all(a)
and(a)
root and logarithm
Generic
matlab
R
Python
gnuplot
idl
Axiom
Maxima
Maple
Mathematica
bc
Square root
sqrt(a)
sqrt(a)
sqrt(a)
math.sqrt(a)
sqrt(a)
sqrt(a)
sqrt(a)
sqrt(a)
sqrt(a)
Sqrt[a]
sqrt(a)
√
a
Generic
matlab
R
Python
gnuplot
idl
Axiom
Maxima
Maple
Mathematica
MuPAD
bc
Logarithm, base e (natural)
log(a)
log(a)
log(a)
math.log(a)
log(a)
alog(a)
log(a)
log(a)
log(a)
Log[a]
ln(a)
l(a)
ln a = loge a
Generic
matlab
R
Python
gnuplot
idl
Logarithm, base 
log10(a)
log10(a)
log10(a)
math.log10(a)
log10(a)
alog10(a)
log10 a
matlab
R
Python
Logarithm, base  (binary)
log2(a)
log2(a)
math.log(a, 2)
log2 a
Generic
matlab
R
Python
gnuplot
idl
bc
Exponential function
exp(a)
exp(a)
exp(a)
math.exp(a)
exp(a)
exp(a)
e(a)
ea
2.5
Round off
matlab
R
Python
idl
Round
round(a)
round(a)
around(a) or math.round(a)
round(a)
matlab
R
Python
gnuplot
idl
Round up
ceil(a)
ceil(a)
ceil(a)
ceil(a)
ceil(a)
matlab
R
Python
gnuplot
idl
Round down
floor(a)
floor(a)
floor(a)
floor(a)
floor(a)
matlab
Python
Round towards zero
fix(a)
fix(a)
5
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
2.6
Mathematical constants
matlab
Scilab
R
Python
idl
Axiom
Maxima
Maple
Mathematica
MuPAD
π = 3.141592
pi
%pi
pi
math.pi
!pi
%pi
%pi
Pi
Pi
PI
matlab
Scilab
R
Python
gnuplot
idl
Axiom
Maxima
Maple
Mathematica
MuPAD
e = 2.718281
exp(1)
%e
exp(1)
math.e or math.exp(1)
exp(1)
exp(1)
%e
%e
exp(1)
E
E
2.6.1
Missing values; IEEE-754 floating point status flags
matlab
Python
Scilab
Not a Number
NaN
nan
%nan
matlab
Scilab
Python
Infinity, ∞
Inf
%inf
inf
Python
Axiom
Infinity, +∞
plus_inf
%plusInfinity
Python
Axiom
Infinity, −∞
minus_inf
%minusInfinity
Python
Plus zero, +0
plus_zero
Python
Minus zero, −0
minus_zero
2.7
Complex numbers
matlab
Scilab
R
Python
gnuplot
idl
Axiom
Maxima
Imaginary unit
i
%i
1i
z = 1j
{0,1}
complex(0,1)
%i
%i
matlab
Scilab
R
Python
gnuplot
idl
Axiom
Maxima
A complex number, 3 + 4i
z = 3+4i
z = 3+4*%i
z <- 3+4i
z = 3+4j or z = complex(3,4)
{3,4}
z = complex(3,4)
3+4*%i
3+4*%i
Generic
matlab
R
Python
gnuplot
idl
Maxima
Absolute value (modulus)
abs(z)
abs(z)
abs(3+4i) or Mod(3+4i)
abs(3+4j)
abs({3,4})
abs(z)
abs(z);
Generic
matlab
R
Python
gnuplot
idl
Maxima
Real part
real(z)
real(z)
Re(3+4i)
z.real
real({3,4})
real_part(z)
realpart(z)
i=
√
−1
6
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
Generic
matlab
R
Python
idl
gnuplot
Maxima
Imaginary part
imag(z)
imag(z)
Im(3+4i)
z.imag
imaginary(z)
imag({3,4})
imagpart(z)
matlab
R
gnuplot
Argument
arg(z)
Arg(3+4i)
arg({3,4})
Generic
matlab
R
Python
idl
Complex conjugate
conj(z)
conj(z)
Conj(3+4i)
z.conj(); z.conjugate()
conj(z)
2.8
Trigonometry
Generic
Sine
sin(a)
Generic
Cosine
cos(a)
Generic
Tangent
tan(a)
Generic
Arcsine
asin(a) or arcsin(a)
Generic
Arccosine
acos(a) or arccos(a)
Generic
Arctangent
atan(a) or arctan(a)
matlab
R
Python
Arctangent, arctan(b/a)
atan(a,b)
atan2(b,a)
atan2(b,a)
Generic
Hyperbolic sine
sinh(a)
Generic
Hyperbolic cosine
cosh(a)
Generic
Hyperbolic tangent
tanh(a)
Python
Hypotenus; Euclidean distance
hypot(x,y)
2.9
Generate random numbers
matlab
Scilab
R
Python
Uniform distribution
rand(1,10)
rand(1,10,’uniform’)
runif(10)
random.random((10,))
random.uniform((10,))
idl
randomu(seed, 10)
matlab
Scilab
R
Python
Uniform: Numbers between  and 
2+5*rand(1,10)
2+5*rand(1,10,’uniform’)
runif(10, min=2, max=7)
random.uniform(2,7,(10,))
idl
2+5*randomu(seed, 10)
matlab
Scilab
R
Python
Uniform: , array
rand(6)
rand(6,6,’uniform’)
matrix(runif(36),6)
random.uniform(0,1,(6,6))
idl
randomu(seed,[6,6])
matlab
Scilab
R
Python
Normal distribution
randn(1,10)
rand(1,10,’normal’)
rnorm(10)
random.standard_normal((10,))
idl
randomn(seed, 10)
p
x2 + y 2
7
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
3
Vectors
matlab
R
Python
idl
Row vector, 1 × n-matrix
a=[2 3 4 5];
a <- c(2,3,4,5)
a=array([2,3,4,5])
a = [2, 3, 4, 5]
matlab
R
Python
Column vector, m × 1-matrix
adash=[2 3 4 5]’;
adash <- t(c(2,3,4,5))
array([2,3,4,5])[:,NewAxis]
array([2,3,4,5]).reshape(-1,1)
r_[1:10,’c’]
idl
transpose([2,3,4,5])
3.1
Sequences
matlab
R
Python
idl
,,, ... ,
1:10
seq(10) or 1:10
arange(1,11, dtype=Float)
range(1,11)
indgen(10)+1
dindgen(10)+1
matlab
R
Python
idl
.,.,., ... ,.
0:9
seq(0,length=10)
arange(10.)
dindgen(10)
matlab
R
Python
idl
,,,
1:3:10
seq(1,10,by=3)
arange(1,11,3)
indgen(4)*3+1
matlab
R
Python
,,, ... ,
10:-1:1
seq(10,1) or 10:1
arange(10,0,-1)
matlab
R
Python
,,,
10:-3:1
seq(from=10,to=1,by=-3)
arange(10,0,-3)
matlab
R
Python
Linearly spaced vector of n= points
linspace(1,10,7)
seq(1,10,length=7)
linspace(1,10,7)
matlab
Scilab
R
Python
idl
Reverse
reverse(a)
a($:-1:1)
rev(a)
a[::-1] or
reverse(a)
matlab
Python
Set all values to same scalar value
a(:) = 3
a.fill(3), a[:] = 3
3.2
Concatenation (vectors)
matlab
R
Python
idl
Concatenate two vectors
[a a]
c(a,a)
concatenate((a,a))
[a,a] or rebin(a,2,size(a))
matlab
R
Python
idl
[1:4 a]
c(1:4,a)
concatenate((range(1,5),a), axis=1)
[indgen(3)+1,a]
3.3
Repeating
matlab
R
Python
  ,   
[a a]
rep(a,times=2)
concatenate((a,a))
R
Python
  ,   ,   
rep(a,each=3)
a.repeat(3) or
8
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
R
Python
3.4
,  ,   
rep(a,a)
a.repeat(a) or
Miss those elements out
matlab
Scilab
R
Python
miss the first element
a(2:end)
a(2:$)
a[-1]
a[1:]
matlab
R
miss the tenth element
a([1:9])
a[-10]
R
miss ,,, ...
a[-seq(1,50,3)]
matlab
Scilab
Python
last element
a(end)
a($)
a[-1]
matlab
Python
last two elements
a(end-1:end)
a[-2:]
3.5
Maximum and minimum
matlab
Python
R
pairwise max
max(a,b)
maximum(a,b)
pmax(a,b)
matlab
Python
R
max of all values in two vectors
max([a b])
concatenate((a,b)).max()
max(a,b)
matlab
Python
R
[v,i] = max(a)
v,i = a.max(0),a.argmax(0)
v <- max(a) ; i <- which.max(a)
3.6
Vector multiplication
matlab
R
Python
Multiply two vectors
a.*a
a*a
a*a
idl
Mathematica
Vector cross product, u × v
crossp(u,v)
cross(u,v)
matlab
Python
Vector dot product, u · v
dot(u,v)
dot(u,v)
4
Matrices
matlab
R
Python
idl
Axiom
Maxima
Maple
Mathematica
Derive
4.1
Define a matrix
a = [2 3;4 5]
rbind(c(2,3),c(4,5))
array(c(2,3,4,5), dim=c(2,2))
a = array([[2,3],[4,5]])
a = [[2,3],[4,5]]
a := matrix [[2,3],[4,5]]
matrix([2,3],[4,5])
matrix([[2,3],[4,5]])
{{2,3},{4,5}}
[[2,3],[4,5]]
Concatenation (matrices); rbind and cbind
matlab
R
Python
Bind rows
[a ; b]
rbind(a,b)
concatenate((a,b), axis=0)
vstack((a,b))
matlab
R
Python
Bind columns
[a , b]
cbind(a,b)
concatenate((a,b), axis=1)
hstack((a,b))
h
2
4
3
5
i
9
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
Python
matlab
Python
Bind slices (three-way arrays)
concatenate((a,b), axis=2)
dstack((a,b))
Concatenate matrices into one vector
[a(:), b(:)]
concatenate((a,b), axis=None)
Bind rows (from vectors)
[1:4 ; 1:4]
rbind(1:4,1:4)
concatenate((r_[1:5],r_[1:5])).reshape(2,-1)
vstack((r_[1:5],r_[1:5]))
[,1] [,2] [,3] [,4]
[1,]
1
2
3
4
[2,]
1
2
3
4
matlab
R
Python
Bind columns (from vectors)
matlab
[1:4 ; 1:4]’
R
cbind(1:4,1:4)
[,1] [,2]
[1,]
1
1
[2,]
2
2
[3,]
3
3
[4,]
4
4
4.2
Array creation
matlab
R
Python
idl
 filled array
zeros(3,5)
matrix(0,3,5) or array(0,c(3,5))
zeros((3,5),Float)
dblarr(3,5)
Python
idl
 filled array of integers
zeros((3,5))
intarr(3,5)
matlab
R
Python
idl
 filled array
ones(3,5)
matrix(1,3,5) or array(1,c(3,5))
ones((3,5),Float)
dblarr(3,5)+1
matlab
R
Python
idl
Any number filled array
ones(3,5)*9
matrix(9,3,5) or array(9,c(3,5))
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
9
9
9
9
9
9
9
9
9
9
9
9
9
9
9
1
0
0
0
1
0
0
0
1
4
0
0
0
5
0
0
0
6
8
3
4
1
5
9
6
7
2
h
1
4
2
5
3
6
i
h
1
2
3
4
5
6
i
1
2
3
intarr(3,5)+9
matlab
Scilab
R
Python
idl
Identity matrix
eye(3)
eye(3,3)
diag(1,3)
identity(3)
identity(3)
matlab
R
Python
idl
Axiom
Diagonal
diag([4 5 6])
diag(c(4,5,6))
diag((4,5,6))
diag_matrix([4,5,6])
diagonalMatrix([4,5,6])
matlab
Scilab
Magic squares; Lo Shu
magic(3)
testmatrix(’magi’,3)
Python
Empty array
a = empty((3,3))
4.3
Reshape and flatten matrices
matlab
Scilab
R
Python
idl
Reshaping (rows first)
reshape(1:6,3,2)’;
matrix(1:6,3,2)’;
matrix(1:6,nrow=3,byrow=T)
arange(1,7).reshape(2,-1)
a.setshape(2,3)
reform(a,2,3)
Python
Reshaping (columns first)
reshape(1:6,2,3);
matrix(1:6,2,3);
matrix(1:6,nrow=2)
array(1:6,c(2,3))
arange(1,7).reshape(-1,2).transpose()
matlab
R
Python
Flatten to vector (by rows, like comics)
a’(:)
as.vector(t(a))
a.flatten() or
matlab
Scilab
R
4
5
6
10
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
matlab
R
Python
Flatten to vector (by columns)
a(:)
as.vector(a)
a.flatten(1)
matlab
R
Flatten upper triangle (by columns)
vech(a)
a[row(a) <= col(a)]
4.4
1
a11
a21
a31
4
2
5
3
6
Shared data (slicing)
matlab
R
Python
4.5
Copy of a
b = a
b = a
b = a.copy()
Indexing and accessing elements (Python: slicing)
matlab
R
Python
idl
Input is a , array
a = [ 11 12 13 14 ...
21 22 23 24 ...
31 32 33 34 ]
a <- rbind(c(11, 12, 13,
c(21, 22, 23,
c(31, 32, 33,
a = array([[ 11, 12, 13,
[ 21, 22, 23,
[ 31, 32, 33,
a = [[ 11, 12, 13, 14 ],
[ 21, 22, 23, 24 ],
[ 31, 32, 33, 34 ]]
14),
24),
34))
14 ],
24 ],
34 ]])
$
$
a12
a22
a32
a13
a23
a33
a14
a24
a34
a12
a13
a14
matlab
R
Python
idl
Element , (row,col)
a(2,3)
a[2,3]
a[1,2]
a(2,1)
a23
matlab
R
Python
idl
First row
a(1,:)
a[1,]
a[0,]
a(*,0)
a11
matlab
R
Python
idl
First column
a(:,1)
a[,1]
a[:,0]
a(0,*)
a11
a21
a31
matlab
Python
Array as indices
a([1 3],[1 4]);
a.take([0,2]).take([0,3], axis=1)
h
a11
a31
a14
a34
matlab
Scilab
R
Python
idl
All, except first row
a(2:end,:)
a(2:$,:)
a[-1,]
a[1:,]
a(*,1:*)
h
a21
a31
a22
a32
a23
a33
a24
a34
i
Last two rows
a(end-1:end,:)
a[-2:,]
h
a21
a31
a22
a32
a23
a33
a24
a34
i
matlab
Python
Strides: Every other row
a(1:2:end,:)
a[::2,:]
h
a11
a31
a12
a32
a13
a33
a14
a34
i
matlab
Python
Python
Third in last dimension (axis)
a[...,2]
h
a11
a31
a13
a33
a14
a34
i
R
All, except row,column (,)
a[-2,-3]
matlab
R
Python
Remove one column
a(:,[1 3 4])
a[,-2]
a.take([0,2,3],axis=1)
a11
a21
a31
a13
a23
a33
a14
a24
a34
Diagonal
a.diagonal(offset=0)
Python
a11
a22
a33
4.6
Assignment
matlab
R
Python
a(:,1) = 99
a[,1] <- 99
a[:,0] = 99
i
a44
11
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
matlab
R
Python
a(:,1) = [99 98 97]’
a[,1] <- c(99,98,97)
a[:,0] = array([99,98,97])
matlab
R
Python
Clipping: Replace all elements over 
a(a>90) = 90;
a[a>90] <- 90
(a>90).choose(a,90)
a.clip(min=None, max=90)
idl
a>90
Python
Clip upper and lower values
a.clip(min=2, max=5)
idl
a < 2 > 5
4.7
Transpose and inverse
matlab
R
Python
Transpose
a’
t(a)
a.conj().transpose()
idl
Maxima
transpose(a)
transpose(a);
matlab
Python
Non-conjugate transpose
a.’ or transpose(a)
a.transpose()
matlab
R
Python
idl
Axiom
Maxima
Determinant
det(a)
det(a)
linalg.det(a) or determinant(a)
determ(a)
determinant a
determinant(a);
matlab
R
Python
idl
Axiom
Maxima
Inverse
inv(a)
solve(a)
linalg.inv(a) or inverse(a)
invert(a)
inverse a
invert(a),detout;
matlab
R
Python
Pseudo-inverse
pinv(a)
ginv(a)
linalg.pinv(a)
matlab
Python
Norms
norm(a)
norm(a)
matlab
Scilab
R
Python
idl
Mathematica
Axiom
Eigenvalues
eig(a)
spec(a)
eigen(a)$values
linalg.eig(a)[0]
eigenvalues(a)
hqr(elmhes(a))
Eigenvalues[matrix]
eigenvalues a
idl
Mathematica
Singular values
svd(a)
svd(a)$d
linalg.svd(a)
singular_value_decomposition(a)
svdc,A,w,U,V
SingularValueDecomposition[m]
matlab
Python
Cholesky factorization
chol(a)
linalg.cholesky(a)
matlab
R
Python
Axiom
Eigenvectors
[v,l] = eig(a)
[v,l] = spec(a)
eigen(a)$vectors
linalg.eig(a)[1]
eigenvectors(a)
eigenvectors a
matlab
R
Python
Rank
rank(a)
rank(a)
rank(a)
matlab
Scilab
R
Python
12
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
4.8
Sum
matlab
Scilab
R
Python
idl
Sum of each column
sum(a)
sum(a,’c’)
apply(a,2,sum)
a.sum(axis=0)
total(a,2)
matlab
Scilab
R
Python
idl
Sum of each row
sum(a’)
sum(a,’r’)
apply(a,1,sum)
a.sum(axis=1)
total(a,1)
matlab
Scilab
R
Python
idl
Sum of all elements
sum(sum(a))
sum(a)
sum(a)
a.sum()
total(a)
Python
Sum along diagonal
a.trace(offset=0)
matlab
R
Python
Cumulative sum (columns)
cumsum(a)
apply(a,2,cumsum)
a.cumsum(axis=0)
4.9
Sorting
matlab
Python
Example data
a = [ 4 3 2 ; 2 8 6 ; 1 4 7 ]
a = array([[4,3,2],[2,8,6],[1,4,7]])
matlab
Scilab
R
Python
Flat and sorted
sort(a(:))
s=sort(a(:)); s($:-1:1)
t(sort(a))
a.ravel().sort() or
matlab
Scilab
R
Python
idl
Sort each column
sort(a)
s=sort(a,’r’); s($:-1:1,:)
apply(a,2,sort)
a.sort(axis=0) or msort(a)
sort(a)
matlab
Scilab
R
Python
Sort each row
sort(a’)’
s=sort(a,’c’); s(:,$:-1:1)
t(apply(a,1,sort))
a.sort(axis=1)
matlab
Python
Sort rows (by first row)
sortrows(a,1)
a[a[:,0].argsort(),]
R
Python
Sort, return indices
order(a)
a.ravel().argsort()
Python
Sort each column, return indices
a.argsort(axis=0)
Python
Sort each row, return indices
a.argsort(axis=1)
4.10
Maximum and minimum
matlab
Scilab
R
Python
idl
max in each column
max(a)
max(a,’c’)
apply(a,2,max)
a.max(0) or amax(a [,axis=0])
max(a,DIMENSION=2)
matlab
Scilab
R
Python
idl
max in each row
max(a’)
max(a,’r’)
apply(a,1,max)
a.max(1) or amax(a, axis=1)
max(a,DIMENSION=1)
matlab
Scilab
R
Python
idl
max in array
max(max(a))
max(a)
max(a)
a.max() or
max(a)
4
2
1
3
8
4
2
6
7
1
3
6
2
4
7
2
4
8
1
2
4
3
4
8
2
6
7
2
2
1
3
6
4
4
8
7
1
2
4
4
8
3
7
6
2
13
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
matlab
Scilab
R
return indices, i
[v i] = max(a)
[v,i] = max(a,’c’)
i <- apply(a,1,which.max)
matlab
Python
R
pairwise max
max(b,c)
maximum(b,c)
pmax(b,c)
matlab
R
cummax(a)
apply(a,2,cummax)
Python
max-to-min range
a.ptp(); a.ptp(0)
4.11
Matrix manipulation
matlab
Scilab
R
Python
idl
Flip left-right
fliplr(a)
a(:,$:-1:1) or mtlb_fliplr(a)
a[,4:1]
fliplr(a) or a[:,::-1]
reverse(a)
matlab
Scilab
R
Python
idl
Flip up-down
flipud(a)
a($:-1:1,:)
a[3:1,]
flipud(a) or a[::-1,]
reverse(a,2)
matlab
Scilab
Python
idl
Rotate  degrees
rot90(a)
--rot90(a)
rotate(a,1)
matlab
Scilab
Octave
Python
R
Repeat matrix: [ a a a ; a a a ]
repmat(a,2,3)
mtlb_repmat(a,2,3)
kron(ones(2,3),a)
kron(ones((2,3)),a)
kronecker(matrix(1,2,3),a)
matlab
R
Python
Mathematica
Triangular, upper
triu(a)
a[lower.tri(a)] <- 0
triu(a)
UpperDiagonalMatrix[f, n]
matlab
R
Python
Triangular, lower
tril(a)
a[upper.tri(a)] <- 0
tril(a)
4.12
Equivalents to ”size”
matlab
R
Python
idl
Matrix dimensions
size(a)
dim(a)
a.shape or a.getshape()
size(a)
matlab
R
Python
idl
Axiom
Maxima
Maple
Mathematica
Derive
Number of columns
size(a,2) or length(a)
ncol(a)
a.shape[1] or size(a, axis=1)
s=size(a) & s[1]
ncols(m)
mat_ncols(m)
linalg[coldim](m)
Dimensions[m][[2]]
DIMENSION(m SUB 1)
matlab
Scilab
R
Python
idl
Number of elements
length(a(:))
length(a)
prod(dim(a))
a.size or size(a[, axis=None])
n_elements(a)
matlab
Python
Number of dimensions
ndims(a)
a.ndim
R
Python
Number of bytes used in memory
object.size(a)
a.nbytes
14
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
4.13
Matrix- and elementwise- multiplication
matlab
R
Python
Elementwise operations
a .* b
a * b
a * b or multiply(a,b)
matlab
R
Python
idl
Axiom
Maxima
Maple
Mathematica
Matrix product (dot product)
a * b
a %*% b
matrixmultiply(a,b)
a # b or b ## a
a*b
a.b
evalm(a &* b)
a.b
Python
idl
Inner matrix vector multiplication a · b0
inner(a,b) or
transpose(a) # b
R
Python
idl
h
1
9
h
7
15
10
22
i
h
5
11
11
25
i
Outer product
outer(a,b) or a %o% b
outer(a,b) or
a # b
"
1
2
3
4
Cross product
crossprod(a,b) or t(a) %*% b
h
R
10
14
matlab
Scilab
R
Python
Kronecker product
kron(a,b)
kron(a,b) or a .*. b
kronecker(a,b)
kron(a,b)
"
1
3
3
9
matlab
Matrix division, b·a−1
a / b
idl
Left matrix division, b−1 ·a
(solve linear equations)
a \ b
linsolve(a,b)
solve(a,b)
linalg.solve(a,b)
solve_linear_equations(a,b)
cramer(a,b)
Python
Vector dot product
vdot(a,b)
Python
Cross product
cross(a,b)
matlab
Scilab
R
Python
4.14
matlab
R
Python
matlab
R
Python
idl
Find; conditional indexing
Non-zero elements, indices
find(a)
which(a != 0)
a.ravel().nonzero()
nonzero(a.flat)
Non-zero elements, array indices
[i j] = find(a)
which(a != 0, arr.ind=T)
(i,j) = a.nonzero()
(i,j) = where(a!=0)
(i,j) = nonzero(a)
where(a NE 0)
matlab
R
Python
Vector of non-zero values
[i j v] = find(a)
ij <- which(a != 0, arr.ind=T); v <- a[ij]
v = a.compress((a!=0).flat)
v = extract(a!=0,a)
idl
a(where(a NE 0))
matlab
R
Python
Condition, indices
find(a>5.5)
which(a>5.5)
(a>5.5).nonzero()
idl
where(a GE 5.5)
R
Python
Return values
ij <- which(a>5.5, arr.ind=T); v <- a[ij]
a.compress((a>5.5).flat)
idl
a(where(a GE 5.5))
matlab
Python
Zero out elements above .
a .* (a>5.5)
where(a>5.5,0,a) or a * (a>5.5)
5
16
Ax = b
2
4
6
8
14
20
2
4
6
12
i
3
6
9
12
4
8
12
16
#
i
2
6
4
12
4
8
8
16
#
15
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
Python
5
Replace values
a.put(2,indices)
Multi-way arrays
matlab
Python
Define a -way array
a = cat(3, [1 2; 1 2],[3 4; 3 4]);
a = array([[[1,2],[1,2]], [[3,4],[3,4]]])
matlab
Python
a(1,:,:)
a[0,...]
6
File input and output
idl
Reading from a file (d)
f = load(’data.txt’)
f <- read.table("data.txt")
f = fromfile("data.txt")
f = load("data.txt")
read()
matlab
R
Python
idl
Reading from a file (d)
f = load(’data.txt’)
f <- read.table("data.txt")
f = load("data.txt")
read()
matlab
R
Python
gnuplot
idl
Reading fram a CSV file (d)
x = dlmread(’data.csv’, ’;’)
f <- read.table(file="data.csv", sep=";")
f = load(’data.csv’, delimiter=’;’)
set datafile separator ";"
x = read_ascii(data_start=1,delimiter=’;’)
matlab
R
Python
Writing to a file (d)
save -ascii data.txt f
write(f,file="data.txt")
save(’data.csv’, f, fmt=’%.6f’, delimiter=’;’)
Python
Writing to a file (d)
f.tofile(file=’data.csv’, format=’%.6f’, sep=’;’)
Python
Reading from a file (d)
f = fromfile(file=’data.csv’, sep=’;’)
matlab
R
Python
7
7.1
Plotting
Basic x-y plots
4
3
matlab
R
Python
idl
d line plot
plot(a)
plot(a, type="l")
plot(a)
plot, a
2
1
0
-1
-2
-3
-4
0
20
40
60
80
100
4.5
matlab
R
Python
idl
d scatter plot
plot(x(:,1),x(:,2),’o’)
plot(x[,1],x[,2])
plot(x[:,0],x[:,1],’o’)
plot, x(1,*), x(2,*)
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
4.5
5.0
5.5
6.0
6.5
7.0
7.5
8.0
7
6
matlab
Python
Two graphs in one plot
plot(x1,y1, x2,y2)
plot(x1,y1,’bo’, x2,y2,’go’)
5
4
3
2
1
4.0
16
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
matlab
R
Python
idl
Overplotting: Add new plots to current
plot(x1,y1)
hold on
plot(x2,y2)
plot(x1,y1)
matplot(x2,y2,add=T)
plot(x1,y1,’o’)
plot(x2,y2,’o’)
show() # as normal
plot, x1, y1
oplot, x2, y2
matlab
Python
idl
subplots
subplot(211)
subplot(211)
!p.multi(0,2,1)
matlab
R
Python
idl
Plotting symbols and color
plot(x,y,’ro-’)
plot(x,y,type="b",col="red")
plot(x,y,’ro-’)
plot, x,y, line=1, psym=-1
7.1.1
matlab
R
Python
matlab
Octave
R
Python
gnuplot
matlab
Scilab
R
gnuplot
Python
idl
matlab
R
idl
Python
idl
7.1.2
Axes and titles
Turn on grid lines
grid on
grid()
grid()
: aspect ratio
axis equal
axis(’equal’)
replot
plot(c(1:10,10:1), asp=1)
figure(figsize=(6,6))
set size ratio -1
Set axes manually
axis([ 0 10 0 5 ])
plot(’axis’,[ 0 10 0 5 ])
plot(x,y, xlim=c(0,10), ylim=c(0,5))
set xrange [0:10]
set yrange [0:5]
axis([ 0, 10, 0, 5 ])
plot, x(1,*), x(2,*),
xran=[0,10], yran=[0,5]
Axis labels and titles
title(’title’)
xlabel(’x-axis’)
ylabel(’y-axis’)
plot(1:10, main="title",
xlab="x-axis", ylab="y-axis")
plot, x,y, title=’title’,
xtitle=’x-axis’, ytitle=’y-axis’
Insert text
text(2,25,’hello’)
xyouts, 2,25, ’hello’
Log plots
matlab
R
Python
idl
logarithmic y-axis
semilogy(a)
plot(x,y, log="y")
semilogy(a)
plot, x,y, /YLOG or plot_io, x,y
matlab
R
Python
idl
logarithmic x-axis
semilogx(a)
plot(x,y, log="x")
semilogx(a)
plot, x,y, /XLOG or plot_oi, x,y
matlab
R
Python
idl
logarithmic x and y axes
loglog(a)
plot(x,y, log="xy")
loglog(a)
plot_oo, x,y
17
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
7.1.3
Filled plots and bar plots
matlab
Octave
R
Python
gnuplot
5
6
7
8
9
10
Stem-and-Leaf plot
stem(x[,3])
R
5
71
033
00113345567889
0133566677788
32674
Functions
gnuplot
Axiom
1.0
●
●
●
●●
●●●
●
●
●
●
●
●
0.5
●
●
●
●●
●●●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●●
●●●●
●
●
●
●
●
●
●
●
f (x)
●
●
●
●
●
●
●
●
●
0.0
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
Python
theta = 0:.001:2*pi;
r = sin(2*theta);
theta = arange(0,2*pi,0.001)
r = sin(2*theta)
matlab
R
idl
hist(randn(1000,1))
hist(rnorm(1000))
plot, histogram(randomn(5,1000))
matlab
R
hist(randn(1000,1), -4:4)
hist(rnorm(1000), breaks= -4:4)
R
hist(rnorm(1000), breaks=c(seq(-5,0,0.25), seq(0.5,5,0.5)), freq=F)
matlab
R
plot(sort(a))
plot(apply(a,1,sort),type="l")
●
●
●
●
●
0
10
20
30
x
ρ(θ) = sin(2θ)
45
180
0
315
270
Histogram plots
●
●
225
7.3
●
●
90
polar(theta, rho)
polarplot(theta, rho)
polar(theta, rho)
set polar
plot sin(2*t)
●
●
135
matlab
Scilab
Python
gnuplot
●
●
Polar plots
matlab
x
5
− cos
●
●
●
−0.5
Octave
Scilab
R
Python
Plot a function for given range
ezplot(f,[0,40])
fplot(’sin(x/3) - cos(x/5)’,[0,40])
% no ezplot
fplot2d([0:.5:40],f)
plot(f, xlim=c(0,40), type=’p’)
x = arrayrange(0,40,.5)
y = sin(x/3) - cos(x/5)
plot(x,y, ’o’)
set xrange [0,40]
plot sin(x/3) - cos(x/5) with points
draw( sin(x/3) - cos(x/5), x=0..40 )
x
3
f (x) = sin
−1.0
matlab
Defining functions
f = inline(’sin(x/3) - cos(x/5)’)
deff(’y = f(x)’,’y = sin(x/3) - cos(x/5)’)
f <- function(x) sin(x/3) - cos(x/5)
−1.5
matlab
Scilab
R
−2.0
7.1.4
7.2
Filled plot
fill(t,s,’b’, t,c,’g’)
% fill has a bug?
plot(t,s, type="n", xlab="", ylab="")
polygon(t,s, col="lightblue")
polygon(t,c, col="lightgreen")
fill(t,s,’b’, t,c,’g’, alpha=0.2)
set xrange [0:3]
set samples 3/.01
plot sin(2*pi*x) with filledcurves,\
sin(4*pi*x) with filledcurves
●●●●
●
40
18
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
3d data
idl
1.0
-1
-0.2
-2
-2
-1
0
1
2
-2
-1
0
1
2
2
1
0
-1
-2
Plot image data
image(z)
colormap(gray)
image(z, col=gray.colors(256))
im = imshow(Z,
interpolation=’bilinear’,
origin=’lower’,
extent=(-3,3,-3,3))
tv, z
loadct,0
0.0
2
6
0.
0.6
0.8
0.8
0
-0.2
-0.4
-0.6
Image with contours
# imshow() and contour() as above
0.2
1
Python
0.8
R
Python
6
0.
0.6
matlab
0
0.8
idl
-0.2
-0.4
Python
Filled contour plot
contourf(z); colormap(gray)
filled.contour(x,y,z,
nlevels=7, color=gray.colors)
contourf(Z, V,
cmap=cm.gray,
origin=’lower’,
extent=(-3,3,-3,3))
contour, z, nlevels=7, /fill
contour, z, nlevels=7, /overplot, /downhill
1
0.2
matlab
R
2
0.0
idl
Contour plot
contour(z)
contour(z)
levels, colls = contour(Z, V,
origin=’lower’, extent=(-3,3,-3,3))
clabel(colls, levels, inline=1,
fmt=’%1.1f’, fontsize=10)
contour, z
-0.6
matlab
R
Python
Contour and image plots
0.4
7.4.1
0.4
7.4
1.0
-1
-0.2
-2
-2
7.4.2
matlab
Python
R
matlab
R
1
2
Direction field vectors
quiver()
champ()
quiver()
Perspective plots of surfaces over the x-y plane
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)
f <- function(x,y) x*exp(-x^2-y^2)
n <- seq(-2,2, length=40)
z <- outer(n,n,f)
Mesh plot
mesh(z)
persp(x,y,z,
theta=30, phi=30, expand=0.6,
ticktype=’detailed’)
2 −y 2
f (x, y) = xe−x
0.4
0.2
0.0
z
Python
idl
0
2
−0.2
1
−0.4
−2
0
y
matlab
Scilab
Python
-1
−1
surface, z
0
−1
x
1
2
0.4
0.2
z
idl
Surface plot
surf(x,y,z) or surfl(x,y,z)
% no surfl()
persp(x,y,z,
theta=30, phi=30, expand=0.6,
col=’lightblue’, shade=0.75, ltheta=120,
ticktype=’detailed’)
shade_surf, z
loadct,3
0.0
2
−0.2
1
−0.4
−2
0
y
matlab
Octave
R
−2
−1
0
−1
x
1
2
−2
19
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
7.4.3
Scatter (cloud) plots
’icc-gamut.csv’
matlab
R
gnuplot
d scatter plot
plot3(x,y,z,’k+’)
cloud(z~x*y)
splot ’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
-60 0
7.5
Save plot to a graphics file
matlab
Octave
R
Python
gnuplot
idl
Python
R
matlab
Python
R
gnuplot
PostScript
plot(1:10)
print -depsc2 foo.eps
gset output "foo.eps"
gset terminal postscript eps
plot(1:10)
postscript(file="foo.eps")
plot(1:10)
dev.off()
savefig(’foo.eps’)
set terminal postscript enhanced eps color
set output ’foo.eps’
plot 1:10
set_plot,’PS’
device, file=’foo.eps’, /land
plot x,y
device,/close & set_plot,’win’
PDF
savefig(’foo.pdf’)
pdf(file=’foo.pdf’)
SVG (vector graphics for www)
savefig(’foo.svg’)
devSVG(file=’foo.svg’)
set terminal svg
set output ’foo.svg’
matlab
matlab
Python
R
gnuplot
Axiom
Maxima
Maple
Mathematica
MuPAD
8
8.1
PNG (raster graphics)
print -dpng foo.png
savefig(’foo.png’)
png(filename = "Rplot%03d.png"
set terminal png medium
set output ’foo.png’
Output TeX/LaTeX math
outputAsTex(e)
tex(e);
latex(e);
TexForm[e]
generate::TeX(e);
Data analysis
Set membership operators
matlab
R
Python
matlab
R
Python
Maxima
matlab
R
Python
Maxima
Create sets
a = [ 1 2 2 5 2 ];
b = [ 2 3 4 ];
a <- c(1,2,2,5,2)
b <- c(2,3,4)
a = array([1,2,2,5,2])
b = array([2,3,4])
a = set([1,2,2,5,2])
b = set([2,3,4])
Set unique
unique(a)
unique(a)
unique1d(a)
unique(a)
set(a)
setify(a)
Set union
union(a,b)
union(a,b)
union1d(a,b)
a.union(b)
union(a,b)
1
2
5
20
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
matlab
R
Python
Maxima
matlab
R
Python
Maxima
Set intersection
intersect(a,b)
intersect(a,b)
intersect1d(a)
a.intersection(b)
intersect(a,b)
Set difference
setdiff(a,b)
setdiff(a,b)
setdiff1d(a,b)
a.difference(b)
setdifference(a,b)
complement(b,a)
matlab
R
Python
Set exclusion
setxor(a,b)
setdiff(union(a,b),intersect(a,b))
setxor1d(a,b)
a.symmetric_difference(b)
matlab
R
Python
True for set member
ismember(2,a)
is.element(2,a) or 2 %in% a
2 in a
setmember1d(2,a)
contains(a,2)
8.2
Statistics
idl
Axiom
Average
mean(a)
apply(a,2,mean)
a.mean(axis=0)
mean(a [,axis=0])
mean(a)
mean a
matlab
R
Python
idl
Axiom
Median
median(a)
apply(a,2,median)
median(a) or median(a [,axis=0])
median(a)
median(a)
matlab
R
Python
idl
Standard deviation
std(a)
apply(a,2,sd)
a.std(axis=0) or std(a [,axis=0])
stddev(a)
matlab
R
Python
idl
Variance
var(a)
apply(a,2,var)
a.var(axis=0) or var(a)
variance(a)
matlab
R
Python
idl
Correlation coefficient
corr(x,y)
cor(x,y)
correlate(x,y) or corrcoef(x,y)
correlate(x,y)
matlab
R
Python
Covariance
cov(x,y)
cov(x,y)
cov(x,y)
matlab
R
Python
8.3
Interpolation and regression
matlab
R
Python
idl
matlab
R
Python
matlab
Python
Straight line fit
z = polyval(polyfit(x,y,1),x)
plot(x,y,’o’, x,z ,’-’)
z <- lm(y~x)
plot(x,y)
abline(z)
(a,b) = polyfit(x,y,1)
plot(x,y,’o’, x,a*x+b,’-’)
poly_fit(x,y,1)
Linear least squares y = ax + b
a = x\y
solve(a,b)
linalg.lstsq(x,y)
(a,b) = linear_least_squares(x,y)[0]
Polynomial fit
polyfit(x,y,3)
polyfit(x,y,3)
21
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
8.4
Non-linear methods
8.4.1
Polynomials, root finding
Scilab
Python
Polynomial
poly(1.,’x’)
poly()
matlab
R
Python
Find zeros of polynomial
roots([1 -1 -1])
polyroot(c(1,-1,-1))
roots()
x2 − x − 1 = 0
Find a zero near x = 1
f = inline(’1/x - (x-1)’)
fzero(f,1)
f (x) =
matlab
Solve symbolic equations
solve(’1/x = x-1’)
1
x
matlab
Python
Evaluate polynomial
polyval([1 2 1 2],1:10)
polyval(array([1,2,1,2]),arange(1,11))
matlab
8.4.2
1
x
− (x − 1)
=x−1
Differential equations
matlab
Python
Discrete difference function and approximate derivative
diff(a)
diff(x, n=1, axis=0)
Solve differential equations
matlab
8.5
Fourier analysis
Generic
matlab
R
Python
idl
Fast fourier transform
fft(a)
fft(a)
fft(a)
fft(a) or fft(a)
fft(a)
matlab
R
Python
idl
Inverse fourier transform
ifft(a)
fft(a, inverse=TRUE)
ifft(a) or inverse_fft(a)
fft(a),/inverse
Python
idl
Linear convolution
convolve(x,y)
convol()
9
Symbolic algebra; calculus
Axiom
Maxima
Decimal output
numeric %
%,numer;
Axiom
Maxima
Maple
Mathematica
MuPAD
reduce
Derive
Simplification
simplify(e) or normalize(e)
ratsimp(e) or radcan(e)
simplify(e)
Simplify[e] or FullSimplify[e]
simplify(e) or normal(e)
e
e
Axiom
Rectangular form
rectform e
matlab
Axiom
Factorization
factor()
factor()
Axiom
Maxima
Maple
MuPAD
Mathematica
Integration of functions
integrate(f(x), x=0..1)
integrate(f(x), x, 0, 1)
int(f(x), x=0..1)
int(f(x), x=0..1)
Integrate[f[x], {x,0,1}]
Axiom
Maxima
Differentiation
differentiate(%,x)
diff(%,x)
Axiom
Taylor/Laurent/etc. series approxmation
series(%,x=0)
Axiom
Solve equations
solve(sys,vars)
Expand
R1
0
f (x)dx
22
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
Laplace transform
laplace(e,t,s)
Axiom
10
Programming
Script file extension
.m
.sce
.R
.py
.gp or .plt
.idlbatch
.mc or .mac
bc
matlab
Scilab
R
Python
gnuplot
idl
Maxima
bc
Derive
reduce
bc
Comment symbol (rest of line)
%
% or #
//
#
#
#
;
-(* .. *)
#
/* .. */
//
/* .. */
# .. #
".."
%
/* .. */
matlab
Octave
Scilab
R
Python
Maxima
Import library functions
% must be in MATLABPATH
% must be in LOADPATH
getf(’foo.sci’)
library(RSvgDevice)
from pylab import *
load(SET);
matlab
Octave
Scilab
R
Python
gnuplot
idl
Axiom
Mathematica
Maple
Maxima
MuPAD
matlab
Scilab
R
Python
10.1
matlab
R
Python
idl
matlab
R
Python
idl
10.2
Eval
string=’a=234’;
eval(string)
eval()
evstr()
execstr()
string <- "a <- 234"
eval(parse(text=string))
string="a=234"
eval(string)
Loops
for-statement
for i=1:5; disp(i); end
for(i in 1:5) print(i)
for i in range(1,6): print(i)
for k=1,5 do print,k
Multiline for statements
for i=1:5
disp(i)
disp(i*2)
end
for(i in 1:5) {
print(i)
print(i*2)
}
for i in range(1,6):
print(i)
print(i*2)
for k=1,5 do begin $
print, i &$
print, i*2 &$
end
Conditionals
matlab
R
Python
idl
if-statement
if 1>0 a=100; end
if (1>0) a <- 100
if 1>0: a=100
if 1 gt 0 then a=100
matlab
idl
if-else-statement
if 1>0 a=100; else a=0; end
if 1 gt 0 then a=100 else a=0
23
MATLAB commands in numerical Python
Vidar Bronken Gundersen /mathesaurus.sf.net
R
gnuplot
idl
10.3
Ternary operator (if?true:false)
ifelse(a>0,a,0)
a>0?a:0
a>0?a:0
Debugging
matlab
R
Axiom
Maxima
Most recent evaluated expression
ans
.Last.value
%
%
matlab
R
idl
List variables loaded into memory
whos or who
objects()
help
matlab
R
Axiom
Clear variable x from memory
clear x or clear [all]
rm(x)
)clear properties x
matlab
R
Python
idl
Print
disp(a)
print(a)
print a
print, a
10.4
Working directory and OS
matlab
R
Python
idl
List files in directory
dir or ls
list.files() or dir()
os.listdir(".")
dir
matlab
R
Python
List script files in directory
what
list.files(pattern="\.r$")
grep.grep("*.py")
matlab
R
Python
gnuplot
idl
Displays the current working directory
pwd
getwd()
os.getcwd()
pwd
sd
matlab
Scilab
R
Python
gnuplot
idl
Axiom
Change working directory
cd foo
chdir(’foo’)
setwd(’foo’)
os.chdir(’foo’)
cd ’foo’
cd,’foo or sd,’foo
)cd "foo"
matlab
Scilab
Octave
R
Python
gnuplot
idl
a > 0?a : 0
Invoke a System Command
!notepad
host(’notepad’)
system("notepad")
system("notepad")
os.system(’notepad’)
os.popen(’notepad’)
!notepad
spawn,’notepad’
 This document is still draft quality. Most d plot examples are made using Matplotlib, and d plots using R or Gnuplot.
 Version number 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/; Maxima .., http://maxima.sf.net/.
 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.
24
Download