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

More Related Content

What's hot

A Gentle Introduction to Coding ... with Python
A Gentle Introduction to Coding ... with PythonA Gentle Introduction to Coding ... with Python
A Gentle Introduction to Coding ... with Python
Tariq Rashid
 
report
reportreport
report
Myungho Jung
 
Computability, turing machines and lambda calculus
Computability, turing machines and lambda calculusComputability, turing machines and lambda calculus
Computability, turing machines and lambda calculus
Edward Blurock
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
Programming Homework Help
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming
Alex Moore
 
A born-again programmer's odyssey
A born-again programmer's odysseyA born-again programmer's odyssey
A born-again programmer's odyssey
Igor Rivin
 
Cs2251 daa
Cs2251 daaCs2251 daa
Using Parallel Computing Platform - NHDNUG
Using Parallel Computing Platform - NHDNUGUsing Parallel Computing Platform - NHDNUG
Using Parallel Computing Platform - NHDNUG
North Houston .NET Users Group
 
Pattern matching
Pattern matchingPattern matching
Pattern matching
shravs_188
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
Piotr Paradziński
 
Chap09alg
Chap09algChap09alg
Chap09alg
Munkhchimeg
 
Python ppt
Python pptPython ppt
Python ppt
Anush verma
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
Karthik Prakash
 
Basic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV SyllabusBasic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV Syllabus
NANDINI SHARMA
 
Tensorflow in practice by Engineer - donghwi cha
Tensorflow in practice by Engineer - donghwi chaTensorflow in practice by Engineer - donghwi cha
Tensorflow in practice by Engineer - donghwi cha
Donghwi Cha
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
Enthought, Inc.
 
Python for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo CruzPython for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo Cruz
rpmcruz
 
Howto argparse
Howto argparseHowto argparse
Howto argparse
Manuel Cueto
 

What's hot (18)

A Gentle Introduction to Coding ... with Python
A Gentle Introduction to Coding ... with PythonA Gentle Introduction to Coding ... with Python
A Gentle Introduction to Coding ... with Python
 
report
reportreport
report
 
Computability, turing machines and lambda calculus
Computability, turing machines and lambda calculusComputability, turing machines and lambda calculus
Computability, turing machines and lambda calculus
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming
 
A born-again programmer's odyssey
A born-again programmer's odysseyA born-again programmer's odyssey
A born-again programmer's odyssey
 
Cs2251 daa
Cs2251 daaCs2251 daa
Cs2251 daa
 
Using Parallel Computing Platform - NHDNUG
Using Parallel Computing Platform - NHDNUGUsing Parallel Computing Platform - NHDNUG
Using Parallel Computing Platform - NHDNUG
 
Pattern matching
Pattern matchingPattern matching
Pattern matching
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
 
Chap09alg
Chap09algChap09alg
Chap09alg
 
Python ppt
Python pptPython ppt
Python ppt
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
 
Basic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV SyllabusBasic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV Syllabus
 
Tensorflow in practice by Engineer - donghwi cha
Tensorflow in practice by Engineer - donghwi chaTensorflow in practice by Engineer - donghwi cha
Tensorflow in practice by Engineer - donghwi cha
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
 
Python for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo CruzPython for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo Cruz
 
Howto argparse
Howto argparseHowto argparse
Howto argparse
 

Viewers also liked

(Slides) Task scheduling algorithm for multicore processor system for minimiz...
(Slides) Task scheduling algorithm for multicore processor system for minimiz...(Slides) Task scheduling algorithm for multicore processor system for minimiz...
(Slides) Task scheduling algorithm for multicore processor system for minimiz...
Naoki Shibata
 
Scheduling
SchedulingScheduling
Final
FinalFinal
Round Robin Scheduling Algorithm (Simulation)
Round Robin Scheduling Algorithm (Simulation)Round Robin Scheduling Algorithm (Simulation)
Round Robin Scheduling Algorithm (Simulation)
Everywhere
 
Intro table ronde 2 (acteurs) - 10ème séminaire Fratel - mesures QoS
Intro table ronde 2 (acteurs) - 10ème séminaire Fratel - mesures QoSIntro table ronde 2 (acteurs) - 10ème séminaire Fratel - mesures QoS
Intro table ronde 2 (acteurs) - 10ème séminaire Fratel - mesures QoS
Jean-Francois Le Bihan
 
Virtual time round-robin scheduler presented by Parang Saraf (CS4204 VT)
Virtual time round-robin scheduler presented by Parang Saraf (CS4204 VT)Virtual time round-robin scheduler presented by Parang Saraf (CS4204 VT)
Virtual time round-robin scheduler presented by Parang Saraf (CS4204 VT)
Parang Saraf
 
Round robin scheduling
Round robin schedulingRound robin scheduling
Round robin scheduling
Raghav S
 
Editorialisation algorithmique
Editorialisation algorithmiqueEditorialisation algorithmique
Editorialisation algorithmique
olivier
 
Ramification of games_round robin_by Lester B. Panem
Ramification of games_round robin_by Lester B. PanemRamification of games_round robin_by Lester B. Panem
Ramification of games_round robin_by Lester B. Panem
lgabp
 
Notes de cours d'ordonnancement
Notes de cours d'ordonnancementNotes de cours d'ordonnancement
Notes de cours d'ordonnancement
ISIG
 
Etude et simulation d'un système MIMO OFDM
Etude et simulation d'un système MIMO OFDMEtude et simulation d'un système MIMO OFDM
Etude et simulation d'un système MIMO OFDM
Mohamed Nadjib Chaabi
 
Multiuser MIMO-OFDM simulation framework in Matlab
Multiuser MIMO-OFDM simulation framework in MatlabMultiuser MIMO-OFDM simulation framework in Matlab
Multiuser MIMO-OFDM simulation framework in Matlab
Pavel Loskot
 
4g lte matlab
4g lte matlab4g lte matlab
4g lte matlab
Hakim Zentani
 
Chap2 ordonnancement
Chap2 ordonnancementChap2 ordonnancement
Chap2 ordonnancement
michel martiz
 
Matlab code
Matlab codeMatlab code
Matlab code
abdalla472
 
Single Elimination
Single EliminationSingle Elimination
Single Elimination
Glee Sah
 
TP1 Traitement d'images Génie Logiciel avec Matlab
TP1 Traitement d'images Génie Logiciel avec MatlabTP1 Traitement d'images Génie Logiciel avec Matlab
TP1 Traitement d'images Génie Logiciel avec Matlab
Mariem ZAOUALI
 
Simulation of A Communications System Using Matlab
Simulation of A Communications System Using MatlabSimulation of A Communications System Using Matlab
Simulation of A Communications System Using Matlab
Polytechnique Montreal
 
Wireless Channel Modeling - MATLAB Simulation Approach
Wireless Channel Modeling - MATLAB Simulation ApproachWireless Channel Modeling - MATLAB Simulation Approach
Wireless Channel Modeling - MATLAB Simulation Approach
Jayamohan Govindaraj
 

Viewers also liked (20)

(Slides) Task scheduling algorithm for multicore processor system for minimiz...
(Slides) Task scheduling algorithm for multicore processor system for minimiz...(Slides) Task scheduling algorithm for multicore processor system for minimiz...
(Slides) Task scheduling algorithm for multicore processor system for minimiz...
 
Scheduling
SchedulingScheduling
Scheduling
 
Final
FinalFinal
Final
 
Round Robin Scheduling Algorithm (Simulation)
Round Robin Scheduling Algorithm (Simulation)Round Robin Scheduling Algorithm (Simulation)
Round Robin Scheduling Algorithm (Simulation)
 
Intro table ronde 2 (acteurs) - 10ème séminaire Fratel - mesures QoS
Intro table ronde 2 (acteurs) - 10ème séminaire Fratel - mesures QoSIntro table ronde 2 (acteurs) - 10ème séminaire Fratel - mesures QoS
Intro table ronde 2 (acteurs) - 10ème séminaire Fratel - mesures QoS
 
Virtual time round-robin scheduler presented by Parang Saraf (CS4204 VT)
Virtual time round-robin scheduler presented by Parang Saraf (CS4204 VT)Virtual time round-robin scheduler presented by Parang Saraf (CS4204 VT)
Virtual time round-robin scheduler presented by Parang Saraf (CS4204 VT)
 
Round robin scheduling
Round robin schedulingRound robin scheduling
Round robin scheduling
 
Editorialisation algorithmique
Editorialisation algorithmiqueEditorialisation algorithmique
Editorialisation algorithmique
 
Ramification of games_round robin_by Lester B. Panem
Ramification of games_round robin_by Lester B. PanemRamification of games_round robin_by Lester B. Panem
Ramification of games_round robin_by Lester B. Panem
 
Notes de cours d'ordonnancement
Notes de cours d'ordonnancementNotes de cours d'ordonnancement
Notes de cours d'ordonnancement
 
Etude et simulation d'un système MIMO OFDM
Etude et simulation d'un système MIMO OFDMEtude et simulation d'un système MIMO OFDM
Etude et simulation d'un système MIMO OFDM
 
Multiuser MIMO-OFDM simulation framework in Matlab
Multiuser MIMO-OFDM simulation framework in MatlabMultiuser MIMO-OFDM simulation framework in Matlab
Multiuser MIMO-OFDM simulation framework in Matlab
 
4g lte matlab
4g lte matlab4g lte matlab
4g lte matlab
 
Chap2 ordonnancement
Chap2 ordonnancementChap2 ordonnancement
Chap2 ordonnancement
 
4 g evolution
4 g evolution4 g evolution
4 g evolution
 
Matlab code
Matlab codeMatlab code
Matlab code
 
Single Elimination
Single EliminationSingle Elimination
Single Elimination
 
TP1 Traitement d'images Génie Logiciel avec Matlab
TP1 Traitement d'images Génie Logiciel avec MatlabTP1 Traitement d'images Génie Logiciel avec Matlab
TP1 Traitement d'images Génie Logiciel avec Matlab
 
Simulation of A Communications System Using Matlab
Simulation of A Communications System Using MatlabSimulation of A Communications System Using Matlab
Simulation of A Communications System Using Matlab
 
Wireless Channel Modeling - MATLAB Simulation Approach
Wireless Channel Modeling - MATLAB Simulation ApproachWireless Channel Modeling - MATLAB Simulation Approach
Wireless Channel Modeling - MATLAB Simulation Approach
 

Similar to Matlab python-

matlab-python-xref.pdf
matlab-python-xref.pdfmatlab-python-xref.pdf
matlab-python-xref.pdf
ssuserf07225
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
jovannyflex
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
jovannyflex
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
Amr Rashed
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
Albert Bifet
 
Matlab1
Matlab1Matlab1
Matlab1
guest8ba004
 
Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
Muhammad Rizwan
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
chestialtaff
 
Class 28: Entropy
Class 28: EntropyClass 28: Entropy
Class 28: Entropy
David Evans
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
ShwetaPandey248972
 
Matlab intro
Matlab introMatlab intro
Matlab intro
THEMASTERBLASTERSVID
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
konkatisandeepkumar
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
ssuser772830
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
Rajmohan Madasamy
 
matlab-130408153714-phpapp02_lab123.ppsx
matlab-130408153714-phpapp02_lab123.ppsxmatlab-130408153714-phpapp02_lab123.ppsx
matlab-130408153714-phpapp02_lab123.ppsx
lekhacce
 
Python 3000
Python 3000Python 3000
Python 3000
Bob Chao
 
Matlab basic and image
Matlab basic and imageMatlab basic and image
Matlab basic and image
Divyanshu Rasauria
 
Introduction to Matlab.pdf
Introduction to Matlab.pdfIntroduction to Matlab.pdf
Introduction to Matlab.pdf
ssuser43b38e
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
amanabr
 

Similar to Matlab python- (20)

matlab-python-xref.pdf
matlab-python-xref.pdfmatlab-python-xref.pdf
matlab-python-xref.pdf
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Matlab1
Matlab1Matlab1
Matlab1
 
Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Class 28: Entropy
Class 28: EntropyClass 28: Entropy
Class 28: Entropy
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
Matlab intro
Matlab introMatlab intro
Matlab intro
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
matlab-130408153714-phpapp02_lab123.ppsx
matlab-130408153714-phpapp02_lab123.ppsxmatlab-130408153714-phpapp02_lab123.ppsx
matlab-130408153714-phpapp02_lab123.ppsx
 
Python 3000
Python 3000Python 3000
Python 3000
 
Matlab basic and image
Matlab basic and imageMatlab basic and image
Matlab basic and image
 
Introduction to Matlab.pdf
Introduction to Matlab.pdfIntroduction to Matlab.pdf
Introduction to Matlab.pdf
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 

More from Dr. Volkan OBAN

Conference Paper:IMAGE PROCESSING AND OBJECT DETECTION APPLICATION: INSURANCE...
Conference Paper:IMAGE PROCESSING AND OBJECT DETECTION APPLICATION: INSURANCE...Conference Paper:IMAGE PROCESSING AND OBJECT DETECTION APPLICATION: INSURANCE...
Conference Paper:IMAGE PROCESSING AND OBJECT DETECTION APPLICATION: INSURANCE...
Dr. Volkan OBAN
 
Covid19py Python Package - Example
Covid19py  Python Package - ExampleCovid19py  Python Package - Example
Covid19py Python Package - Example
Dr. Volkan OBAN
 
Object detection with Python
Object detection with Python Object detection with Python
Object detection with Python
Dr. Volkan OBAN
 
Python - Rastgele Orman(Random Forest) Parametreleri
Python - Rastgele Orman(Random Forest) ParametreleriPython - Rastgele Orman(Random Forest) Parametreleri
Python - Rastgele Orman(Random Forest) Parametreleri
Dr. Volkan OBAN
 
Linear Programming wi̇th R - Examples
Linear Programming wi̇th R - ExamplesLinear Programming wi̇th R - Examples
Linear Programming wi̇th R - Examples
Dr. Volkan OBAN
 
"optrees" package in R and examples.(optrees:finds optimal trees in weighted ...
"optrees" package in R and examples.(optrees:finds optimal trees in weighted ..."optrees" package in R and examples.(optrees:finds optimal trees in weighted ...
"optrees" package in R and examples.(optrees:finds optimal trees in weighted ...
Dr. Volkan OBAN
 
k-means Clustering in Python
k-means Clustering in Pythonk-means Clustering in Python
k-means Clustering in Python
Dr. Volkan OBAN
 
Naive Bayes Example using R
Naive Bayes Example using  R Naive Bayes Example using  R
Naive Bayes Example using R
Dr. Volkan OBAN
 
R forecasting Example
R forecasting ExampleR forecasting Example
R forecasting Example
Dr. Volkan OBAN
 
k-means Clustering and Custergram with R
k-means Clustering and Custergram with Rk-means Clustering and Custergram with R
k-means Clustering and Custergram with R
Dr. Volkan OBAN
 
Data Science and its Relationship to Big Data and Data-Driven Decision Making
Data Science and its Relationship to Big Data and Data-Driven Decision MakingData Science and its Relationship to Big Data and Data-Driven Decision Making
Data Science and its Relationship to Big Data and Data-Driven Decision Making
Dr. Volkan OBAN
 
Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.
Dr. Volkan OBAN
 
Scikit-learn Cheatsheet-Python
Scikit-learn Cheatsheet-PythonScikit-learn Cheatsheet-Python
Scikit-learn Cheatsheet-Python
Dr. Volkan OBAN
 
Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet
Dr. Volkan OBAN
 
Pandas,scipy,numpy cheatsheet
Pandas,scipy,numpy cheatsheetPandas,scipy,numpy cheatsheet
Pandas,scipy,numpy cheatsheet
Dr. Volkan OBAN
 
ReporteRs package in R. forming powerpoint documents-an example
ReporteRs package in R. forming powerpoint documents-an exampleReporteRs package in R. forming powerpoint documents-an example
ReporteRs package in R. forming powerpoint documents-an example
Dr. Volkan OBAN
 
ReporteRs package in R. forming powerpoint documents-an example
ReporteRs package in R. forming powerpoint documents-an exampleReporteRs package in R. forming powerpoint documents-an example
ReporteRs package in R. forming powerpoint documents-an example
Dr. Volkan OBAN
 
R-ggplot2 package Examples
R-ggplot2 package ExamplesR-ggplot2 package Examples
R-ggplot2 package Examples
Dr. Volkan OBAN
 
R Machine Learning packages( generally used)
R Machine Learning packages( generally used)R Machine Learning packages( generally used)
R Machine Learning packages( generally used)
Dr. Volkan OBAN
 
treemap package in R and examples.
treemap package in R and examples.treemap package in R and examples.
treemap package in R and examples.
Dr. Volkan OBAN
 

More from Dr. Volkan OBAN (20)

Conference Paper:IMAGE PROCESSING AND OBJECT DETECTION APPLICATION: INSURANCE...
Conference Paper:IMAGE PROCESSING AND OBJECT DETECTION APPLICATION: INSURANCE...Conference Paper:IMAGE PROCESSING AND OBJECT DETECTION APPLICATION: INSURANCE...
Conference Paper:IMAGE PROCESSING AND OBJECT DETECTION APPLICATION: INSURANCE...
 
Covid19py Python Package - Example
Covid19py  Python Package - ExampleCovid19py  Python Package - Example
Covid19py Python Package - Example
 
Object detection with Python
Object detection with Python Object detection with Python
Object detection with Python
 
Python - Rastgele Orman(Random Forest) Parametreleri
Python - Rastgele Orman(Random Forest) ParametreleriPython - Rastgele Orman(Random Forest) Parametreleri
Python - Rastgele Orman(Random Forest) Parametreleri
 
Linear Programming wi̇th R - Examples
Linear Programming wi̇th R - ExamplesLinear Programming wi̇th R - Examples
Linear Programming wi̇th R - Examples
 
"optrees" package in R and examples.(optrees:finds optimal trees in weighted ...
"optrees" package in R and examples.(optrees:finds optimal trees in weighted ..."optrees" package in R and examples.(optrees:finds optimal trees in weighted ...
"optrees" package in R and examples.(optrees:finds optimal trees in weighted ...
 
k-means Clustering in Python
k-means Clustering in Pythonk-means Clustering in Python
k-means Clustering in Python
 
Naive Bayes Example using R
Naive Bayes Example using  R Naive Bayes Example using  R
Naive Bayes Example using R
 
R forecasting Example
R forecasting ExampleR forecasting Example
R forecasting Example
 
k-means Clustering and Custergram with R
k-means Clustering and Custergram with Rk-means Clustering and Custergram with R
k-means Clustering and Custergram with R
 
Data Science and its Relationship to Big Data and Data-Driven Decision Making
Data Science and its Relationship to Big Data and Data-Driven Decision MakingData Science and its Relationship to Big Data and Data-Driven Decision Making
Data Science and its Relationship to Big Data and Data-Driven Decision Making
 
Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.
 
Scikit-learn Cheatsheet-Python
Scikit-learn Cheatsheet-PythonScikit-learn Cheatsheet-Python
Scikit-learn Cheatsheet-Python
 
Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet
 
Pandas,scipy,numpy cheatsheet
Pandas,scipy,numpy cheatsheetPandas,scipy,numpy cheatsheet
Pandas,scipy,numpy cheatsheet
 
ReporteRs package in R. forming powerpoint documents-an example
ReporteRs package in R. forming powerpoint documents-an exampleReporteRs package in R. forming powerpoint documents-an example
ReporteRs package in R. forming powerpoint documents-an example
 
ReporteRs package in R. forming powerpoint documents-an example
ReporteRs package in R. forming powerpoint documents-an exampleReporteRs package in R. forming powerpoint documents-an example
ReporteRs package in R. forming powerpoint documents-an example
 
R-ggplot2 package Examples
R-ggplot2 package ExamplesR-ggplot2 package Examples
R-ggplot2 package Examples
 
R Machine Learning packages( generally used)
R Machine Learning packages( generally used)R Machine Learning packages( generally used)
R Machine Learning packages( generally used)
 
treemap package in R and examples.
treemap package in R and examples.treemap package in R and examples.
treemap package in R and examples.
 

Recently uploaded

Introduction to neural network (Module 1).pptx
Introduction to neural network (Module 1).pptxIntroduction to neural network (Module 1).pptx
Introduction to neural network (Module 1).pptx
archanac21
 
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
hahehot
 
@Call @Girls Kochi 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any Time
@Call @Girls Kochi 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any Time@Call @Girls Kochi 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any Time
@Call @Girls Kochi 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any Time
Escorts service
 
GUIA_LEGAL_CHAPTER_4_FOREIGN TRADE CUSTOMS.pdf
GUIA_LEGAL_CHAPTER_4_FOREIGN TRADE CUSTOMS.pdfGUIA_LEGAL_CHAPTER_4_FOREIGN TRADE CUSTOMS.pdf
GUIA_LEGAL_CHAPTER_4_FOREIGN TRADE CUSTOMS.pdf
ProexportColombia1
 
Unblocking The Main Thread - Solving ANRs and Frozen Frames
Unblocking The Main Thread - Solving ANRs and Frozen FramesUnblocking The Main Thread - Solving ANRs and Frozen Frames
Unblocking The Main Thread - Solving ANRs and Frozen Frames
Sinan KOZAK
 
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model SafePaharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
aarusi sexy model
 
Lecture 3 Biomass energy...............ppt
Lecture 3 Biomass energy...............pptLecture 3 Biomass energy...............ppt
Lecture 3 Biomass energy...............ppt
RujanTimsina1
 
system structure in operating systems.pdf
system structure in operating systems.pdfsystem structure in operating systems.pdf
system structure in operating systems.pdf
zyroxsunny
 
( Call  ) Girls Vasant Kunj Just 9873940964 High Class Model Shneha Patil
( Call  ) Girls Vasant Kunj Just 9873940964 High Class Model Shneha Patil( Call  ) Girls Vasant Kunj Just 9873940964 High Class Model Shneha Patil
( Call  ) Girls Vasant Kunj Just 9873940964 High Class Model Shneha Patil
kinni singh$A17
 
Net Zero Case Study: SRK House and SRK Empire
Net Zero Case Study: SRK House and SRK EmpireNet Zero Case Study: SRK House and SRK Empire
Net Zero Case Study: SRK House and SRK Empire
Global Network for Zero
 
LeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdfLeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdf
pavanaroshni1977
 
Response & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITHResponse & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITH
IIIT Hyderabad
 
Social media management system project report.pdf
Social media management system project report.pdfSocial media management system project report.pdf
Social media management system project report.pdf
Kamal Acharya
 
PMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOCPMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOC
itssurajthakur06
 
Introduction to IP address concept - Computer Networking
Introduction to IP address concept - Computer NetworkingIntroduction to IP address concept - Computer Networking
Introduction to IP address concept - Computer Networking
Md.Shohel Rana ( M.Sc in CSE Khulna University of Engineering & Technology (KUET))
 
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model SafeRohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
binna singh$A17
 
Quadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and ControlQuadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and Control
Blesson Easo Varghese
 
IWISS Catalog 2024
IWISS Catalog 2024IWISS Catalog 2024
IWISS Catalog 2024
Iwiss Tools Co.,Ltd
 
( Call  ) Girls Noida 9873940964 High Profile
( Call  ) Girls Noida 9873940964 High Profile( Call  ) Girls Noida 9873940964 High Profile
( Call  ) Girls Noida 9873940964 High Profile
butwhat24
 
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-IDUNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
GOWSIKRAJA PALANISAMY
 

Recently uploaded (20)

Introduction to neural network (Module 1).pptx
Introduction to neural network (Module 1).pptxIntroduction to neural network (Module 1).pptx
Introduction to neural network (Module 1).pptx
 
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
 
@Call @Girls Kochi 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any Time
@Call @Girls Kochi 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any Time@Call @Girls Kochi 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any Time
@Call @Girls Kochi 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any Time
 
GUIA_LEGAL_CHAPTER_4_FOREIGN TRADE CUSTOMS.pdf
GUIA_LEGAL_CHAPTER_4_FOREIGN TRADE CUSTOMS.pdfGUIA_LEGAL_CHAPTER_4_FOREIGN TRADE CUSTOMS.pdf
GUIA_LEGAL_CHAPTER_4_FOREIGN TRADE CUSTOMS.pdf
 
Unblocking The Main Thread - Solving ANRs and Frozen Frames
Unblocking The Main Thread - Solving ANRs and Frozen FramesUnblocking The Main Thread - Solving ANRs and Frozen Frames
Unblocking The Main Thread - Solving ANRs and Frozen Frames
 
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model SafePaharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
 
Lecture 3 Biomass energy...............ppt
Lecture 3 Biomass energy...............pptLecture 3 Biomass energy...............ppt
Lecture 3 Biomass energy...............ppt
 
system structure in operating systems.pdf
system structure in operating systems.pdfsystem structure in operating systems.pdf
system structure in operating systems.pdf
 
( Call  ) Girls Vasant Kunj Just 9873940964 High Class Model Shneha Patil
( Call  ) Girls Vasant Kunj Just 9873940964 High Class Model Shneha Patil( Call  ) Girls Vasant Kunj Just 9873940964 High Class Model Shneha Patil
( Call  ) Girls Vasant Kunj Just 9873940964 High Class Model Shneha Patil
 
Net Zero Case Study: SRK House and SRK Empire
Net Zero Case Study: SRK House and SRK EmpireNet Zero Case Study: SRK House and SRK Empire
Net Zero Case Study: SRK House and SRK Empire
 
LeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdfLeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdf
 
Response & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITHResponse & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITH
 
Social media management system project report.pdf
Social media management system project report.pdfSocial media management system project report.pdf
Social media management system project report.pdf
 
PMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOCPMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOC
 
Introduction to IP address concept - Computer Networking
Introduction to IP address concept - Computer NetworkingIntroduction to IP address concept - Computer Networking
Introduction to IP address concept - Computer Networking
 
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model SafeRohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
 
Quadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and ControlQuadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and Control
 
IWISS Catalog 2024
IWISS Catalog 2024IWISS Catalog 2024
IWISS Catalog 2024
 
( Call  ) Girls Noida 9873940964 High Profile
( Call  ) Girls Noida 9873940964 High Profile( Call  ) Girls Noida 9873940964 High Profile
( Call  ) Girls Noida 9873940964 High Profile
 
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-IDUNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
UNIT I INCEPTION OF INFORMATION DESIGN 20CDE09-ID
 

Matlab python-

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