Download NumPy for MATLAB users

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Loops
MATLAB/Octave
Python
for i=1:5; disp(i); endfor i in range(1,6):
print(i)
for i=1:5
for i in range(1,6):
disp(i)
print(i)
disp(i*2)
print(i*2)
end
for­statement
NumPy for MATLAB users
Multiline for statements
Help
Description
Conditionals
MATLAB/Octave
Python
if 1>0 a=100; end
if 1>0: a=100
if 1>0 a=100; else a=0;
end
Description
if­statement
if­else­statement
ans
whos or who
clear x or clear [all]
disp(a)
Python
Description
doc
help -i % browse with
Info
help help or doc doc
help plot
help splines or doc
splines
demo
help()
Browse help interactively
help
help(plot) or ?plot
help(pylab)
Help on using help
Help for a function
Help for a toolbox/library package
Demonstration examples
Searching available documentation
Debugging
MATLAB/Octave
MATLAB/Octave
Python
Description
MATLAB/Octave
lookfor plot
help
print a
Most recent evaluated expression
List variables loaded into memory
Clear variable $x$ from memory
Print
which plot
Python
help(); modules
[Numeric]
help(plot)
Description
Search help files
List available packages
Locate functions
Using interactively
Working directory and OS
MATLAB/Octave
Python
Description
MATLAB/Octave
Python
Description
dir or ls
what
pwd
os.listdir(".")
grep.grep("*.py")
os.getcwd()
octave -q
TAB or M-?
foo(.m)
os.chdir('foo')
os.system('notepad')
os.popen('notepad')
ipython -pylab
TAB
execfile('foo.py') or run
foo.py
hist -n
Start session
Auto completion
Run code from file
cd foo
!notepad
system("notepad")
List files in directory
List script files in directory
Displays the current working
directory
Change working directory
Invoke a System Command
CTRL-D
CTRL-Z # windows
sys.exit()
End session
Time­stamp: "2007­11­09T16:46:36 vidar"
©2006 Vidar Bronken Gundersen, /mathesaurus.sf.net
Permission is granted to copy, distribute and/or modify this document as long as the above attribution is retained.
history
diary on [..] diary
off
exit or quit
Command history
Save command history
Operators
MATLAB/Octave
help -
Python
Description
Help on operator syntax
Arithmetic operators
Non­linear methods
MATLAB/Octave
Python
Description
a=1; b=2;
a+b
a-b
a*b
a/b
a .^ b
a=1; b=1
a + b or add(a,b)
a - b or subtract(a,b)
a * b or multiply(a,b)
a / b or divide(a,b)
a ** b
power(a,b)
pow(a,b)
a%b
remainder(a,b)
fmod(a,b)
a+=b or add(a,b,a)
Assignment; defining a number
Addition
Subtraction
Multiplication
Division
Power, $a^b$
rem(a,b)
a+=1
factorial(a)
Remainder
In place operation to save array
creation overhead
Factorial, $n!$
Relational operators
MATLAB/Octave
Python
Description
a == b
a<b
a>b
a <= b
a >= b
a == b or equal(a,b)
a < b or less(a,b)
a > b or greater(a,b)
a <= b or less_equal(a,b)
a >= b or
greater_equal(a,b)
a != b or not_equal(a,b)
Equal
Less than
Greater than
Less than or equal
Greater than or equal
a ~= b
Not Equal
Logical operators
MATLAB/Octave
Python
Description
a && b
a || b
a & b or and(a,b)
a and b
a or b
logical_and(a,b) or a and
b
logical_or(a,b) or a or b
logical_xor(a,b)
logical_not(a) or not a
Short­circuit logical AND
Short­circuit logical OR
Element­wise logical AND
a | b or or(a,b)
xor(a, b)
~a or not(a)
~a or !a
any(a)
all(a)
Element­wise logical OR
Logical EXCLUSIVE OR
Logical NOT
True if any element is nonzero
True if all elements are nonzero
Polynomials, root finding
MATLAB/Octave
Python
Description
Polynomial
Find zeros of
polynomial
Find a zero near $x =
1$
poly()
roots([1 -1 -1]) roots()
f = inline('1/x
- (x-1)')
fzero(f,1)
solve('1/x = x1')
polyval([1 2 1
2],1:10)
Solve symbolic
equations
polyval(array([1,2,1,2]),arange(1,11))Evaluate polynomial
Differential equations
MATLAB/Octave
Python
Description
diff(a)
diff(x, n=1, axis=0)
Discrete difference function and
approximate derivative
Solve differential equations
Fourier analysis
MATLAB/Octave
Python
Description
fft(a)
ifft(a)
fft(a) or
ifft(a) or
convolve(x,y)
Fast fourier transform
Inverse fourier transform
Linear convolution
Symbolic algebra; calculus
MATLAB/Octave
Python
Description
Factorization
factor()
Programming
MATLAB/Octave
Python
Description
.m
%
% or #
% must be in MATLABPATH
% must be in LOADPATH
string='a=234';
eval(string)
.py
#
Script file extension
Comment symbol (rest of line)
from pylab import *
Import library functions
string="a=234"
eval(string)
Eval
root and logarithm
Data analysis
MATLAB/Octave
Python
Description
sqrt(a)
log(a)
log10(a)
log2(a)
exp(a)
math.sqrt(a)
math.log(a)
math.log10(a)
math.log(a, 2)
math.exp(a)
Square root
Logarithm, base $e$ (natural)
Logarithm, base 10
Logarithm, base 2 (binary)
Exponential function
MATLAB/Octave
Python
Description
Set union
round(a)
Round
Set intersection
ceil(a)
floor(a)
fix(a)
around(a) or
math.round(a)
ceil(a)
floor(a)
fix(a)
Set membership operators
MATLAB/Octave
Python
Description
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])
unique1d(a)
unique(a)
set(a)
union1d(a,b)
a.union(b)
intersect1d(a)
a.intersection(b)
setdiff1d(a,b)
a.difference(b)
setxor1d(a,b)
a.symmetric_difference(b)
Create sets
2 in a
setmember1d(2,a)
contains(a,2)
True for set member
unique(a)
union(a,b)
intersect(a,b)
setdiff(a,b)
setxor(a,b)
ismember(2,a)
Set unique
Set difference
Set exclusion
MATLAB/Octave
Python
Description
mean(a)
a.mean(axis=0)
mean(a [,axis=0])
median(a) or median(a
[,axis=0])
a.std(axis=0) or std(a
[,axis=0])
a.var(axis=0) or var(a)
correlate(x,y) or
corrcoef(x,y)
cov(x,y)
Average
std(a)
var(a)
corr(x,y)
cov(x,y)
Mathematical constants
MATLAB/Octave
Python
Description
pi
exp(1)
math.pi
math.e or math.exp(1)
$\pi=3.141592$
$e=2.718281$
Python
MATLAB/Octave
Python
Description
NaN
Inf
nan
inf
plus_inf
minus_inf
plus_zero
minus_zero
Not a Number
Infinity, $\infty$
Infinity, $+\infty$
Infinity, $­\infty$
Plus zero, $+0$
Minus zero, $­0$
MATLAB/Octave
Python
Description
i
z = 3+4i
z = 1j
z = 3+4j or z =
complex(3,4)
abs(3+4j)
z.real
z.imag
Imaginary unit
A complex number, $3+4i$
Median
Standard deviation
Variance
Correlation coefficient
Covariance
Interpolation and regression
MATLAB/Octave
Round up
Round down
Round towards zero
Missing values; IEEE­754 floating point status flags
Statistics
median(a)
Round off
Description
z=
(a,b) = polyfit(x,y,1) Straight line fit
polyval(polyfit(x,y,1),x) plot(x,y,'o',
plot(x,y,'o', x,z ,'-')
x,a*x+b,'-')
Linear least squares $y = ax +
a = x\y
linalg.lstsq(x,y)
b$
Polynomial fit
polyfit(x,y,3)
polyfit(x,y,3)
Complex numbers
abs(z)
real(z)
imag(z)
arg(z)
conj(z)
Absolute value (modulus)
Real part
Imaginary part
Argument
z.conj(); z.conjugate() Complex conjugate
Trigonometry
Perspective plots of surfaces over the x­y plane
MATLAB/Octave
Python
Description
MATLAB/Octave
atan(a,b)
atan2(b,a)
hypot(x,y)
Arctangent, $\arctan(b/a)$
Hypotenus; Euclidean distance
n=-2:.1:2;
n=arrayrange(-2,2,.1)
[x,y] = meshgrid(n,n); [x,y] = meshgrid(n,n)
z=x.*exp(-x.^2-y.^2); z = x*power(math.e,-x**2y**2)
Mesh plot
mesh(z)
Surface plot
surf(x,y,z) or
surfl(x,y,z)
% no surfl()
Generate random numbers
MATLAB/Octave
Python
Description
rand(1,10)
random.random((10,))
random.uniform((10,))
random.uniform(2,7,(10,))
Uniform distribution
2+5*rand(1,10)
rand(6)
randn(1,10)
Uniform: Numbers between
2 and 7
Uniform: 6,6 array
random.uniform(0,1,(6,6))
random.standard_normal((10,))Normal distribution
Vectors
MATLAB/Octave
Python
a=[2 3 4 5];
a=array([2,3,4,5])
adash=[2 3 4 5]';
Description
Row vector, $1 \times n$­
matrix
Column vector, $m \times
array([2,3,4,5])[:,NewAxis]
array([2,3,4,5]).reshape(-1,1)1$­matrix
r_[1:10,'c']
Sequences
MATLAB/Octave
Python
Description
1:10
1,2,3, ... ,10
0:9
1:3:10
10:-1:1
10:-3:1
linspace(1,10,7)
arange(1,11,
dtype=Float)
range(1,11)
arange(10.)
arange(1,11,3)
arange(10,0,-1)
arange(10,0,-3)
linspace(1,10,7)
reverse(a)
a(:) = 3
a[::-1] or
a.fill(3), a[:] = 3
0.0,1.0,2.0, ... ,9.0
1,4,7,10
10,9,8, ... ,1
10,7,4,1
Linearly spaced vector of n=7
points
Reverse
Set all values to same scalar
value
Concatenation (vectors)
MATLAB/Octave
Python
Description
[a a]
[1:4 a]
Concatenate two vectors
concatenate((a,a))
concatenate((range(1,5),a),
axis=1)
Python
Description
Scatter (cloud) plots
MATLAB/Octave
Python
Description
3d scatter plot
plot3(x,y,z,'k+')
Save plot to a graphics file
MATLAB/Octave
Python
plot(1:10)
savefig('foo.eps')
print -depsc2 foo.eps
gset output "foo.eps"
gset terminal
postscript eps
plot(1:10)
savefig('foo.pdf')
savefig('foo.svg')
print -dpng foo.png
savefig('foo.png')
Description
PostScript
PDF
SVG (vector graphics for www)
PNG (raster graphics)
Repeating
Functions
MATLAB/Octave
Python
Description
Defining functions
f = inline('sin(x/3) cos(x/5)')
ezplot(f,[0,40])
x = arrayrange(0,40,.5) Plot a function for given range
fplot('sin(x/3) y = sin(x/3) - cos(x/5)
cos(x/5)',[0,40])
plot(x,y, 'o')
% no ezplot
Polar plots
MATLAB/Octave
Python
theta = 0:.001:2*pi;
r = sin(2*theta);
theta =
arange(0,2*pi,0.001)
r = sin(2*theta)
polar(theta, rho)
polar(theta, rho)
Description
Python
Python
Description
[a a]
concatenate((a,a))
a.repeat(3) or
a.repeat(a) or
1 2 3, 1 2 3
1 1 1, 2 2 2, 3 3 3
1, 2 2, 3 3 3
Miss those elements out
MATLAB/Octave
Python
Description
a(2:end)
a([1:9])
a(end)
a(end-1:end)
a[1:]
miss the first element
miss the tenth element
last element
last two elements
a[-1]
a[-2:]
Maximum and minimum
Histogram plots
MATLAB/Octave
MATLAB/Octave
Description
hist(randn(1000,1))
hist(randn(1000,1), -4:4)
plot(sort(a))
MATLAB/Octave
Python
Description
max(a,b)
max([a b])
[v,i] = max(a)
pairwise max
maximum(a,b)
concatenate((a,b)).max() max of all values in two vectors
v,i = a.max(0),a.argmax(0)
Vector multiplication
3d data
MATLAB/Octave
Python
Description
a.*a
dot(u,v)
a*a
dot(u,v)
Multiply two vectors
Vector dot product, $u \cdot v$
Contour and image plots
MATLAB/Octave
Python
contour(z)
levels, colls = contour(Z, Contour plot
V,
origin='lower', extent=
(-3,3,-3,3))
clabel(colls, levels,
inline=1,
fmt='%1.1f', fontsize=10)
Filled contour plot
contourf(Z, V,
cmap=cm.gray,
origin='lower',
extent=(-3,3,-3,3))
Plot image data
im = imshow(Z,
interpolation='bilinear',
origin='lower',
extent=(-3,3,-3,3))
# imshow() and contour() Image with contours
as above
Direction field vectors
quiver()
contourf(z);
colormap(gray)
image(z)
colormap(gray)
quiver()
Description
Matrices
MATLAB/Octave
Python
Description
a = [2 3;4 5]
a = array([[2,3],[4,5]])Define a matrix
Concatenation (matrices); rbind and cbind
MATLAB/Octave
[a ; b]
Python
concatenate((a,b), axis=0)
vstack((a,b))
[a , b]
concatenate((a,b), axis=1)
hstack((a,b))
concatenate((a,b), axis=2)
dstack((a,b))
[a(:), b(:)] concatenate((a,b), axis=None)
Description
Bind rows
Bind columns
Bind slices (three­
way arrays)
Concatenate
matrices into one
vector
[1:4 ; 1:4] concatenate((r_[1:5],r_[1:5])).reshape(2,-1)Bind rows (from
vectors)
vstack((r_[1:5],r_[1:5]))
Bind columns
[1:4 ; 1:4]'
(from vectors)
Array creation
Plotting
MATLAB/Octave
Python
Description
zeros(3,5)
zeros((3,5),Float)
zeros((3,5))
ones((3,5),Float)
0 filled array
0 filled array of integers
1 filled array
Any number filled array
Identity matrix
Diagonal
Magic squares; Lo Shu
Empty array
ones(3,5)
ones(3,5)*9
eye(3)
diag([4 5 6])
magic(3)
identity(3)
diag((4,5,6))
a = empty((3,3))
Reshape and flatten matrices
MATLAB/Octave
Python
reshape(1:6,3,2)';
Reshaping (rows
arange(1,7).reshape(2,-1)
first)
a.setshape(2,3)
arange(1,7).reshape(-1,2).transpose()Reshaping
(columns first)
Flatten to vector
a.flatten() or
(by rows, like
comics)
Flatten to vector
a.flatten(1)
(by columns)
Flatten upper
triangle (by
columns)
reshape(1:6,2,3);
a'(:)
a(:)
vech(a)
Description
Shared data (slicing)
Basic x­y plots
MATLAB/Octave
Python
Description
plot(a)
plot(x(:,1),x(:,2),'o')
plot(x1,y1, x2,y2)
plot(a)
plot(x[:,0],x[:,1],'o')
plot(x1,y1,'bo',
x2,y2,'go')
plot(x1,y1,'o')
plot(x2,y2,'o')
show() # as normal
subplot(211)
plot(x,y,'ro-')
1d line plot
2d scatter plot
Two graphs in one plot
plot(x1,y1)
hold on
plot(x2,y2)
subplot(211)
plot(x,y,'ro-')
Overplotting: Add new plots
to current
subplots
Plotting symbols and color
Axes and titles
MATLAB/Octave
Python
Description
grid on
axis equal
axis('equal')
replot
axis([ 0 10 0 5 ])
title('title')
xlabel('x-axis')
ylabel('y-axis')
grid()
figure(figsize=(6,6))
Turn on grid lines
1:1 aspect ratio
axis([ 0, 10, 0, 5 ])
Set axes manually
Axis labels and titles
text(2,25,'hello')
Insert text
MATLAB/Octave
Python
Description
Log plots
b=a
b = a.copy()
Copy of a
MATLAB/Octave
Python
Description
semilogy(a)
semilogx(a)
loglog(a)
semilogy(a)
semilogx(a)
loglog(a)
logarithmic y­axis
logarithmic x­axis
logarithmic x and y axes
Filled plots and bar plots
MATLAB/Octave
Python
Description
fill(t,s,'b', t,c,'g') fill(t,s,'b', t,c,'g', Filled plot
% fill has a bug?
alpha=0.2)
Indexing and accessing elements (Python: slicing)
Multi­way arrays
MATLAB/Octave
Python
Description
Define a 3­way array
a = cat(3, [1 2; 1 2], a = array([[[1,2],
[3 4; 3 4]);
[1,2]], [[3,4],[3,4]]])
a(1,:,:)
a[0,...]
File input and output
MATLAB/Octave
Python
Description
f = fromfile("data.txt") Reading from a file (2d)
f = load("data.txt")
Reading from a file (2d)
f = load('data.txt')
f = load("data.txt")
Reading fram a CSV file
x = dlmread('data.csv', f = load('data.csv',
(2d)
';')
delimiter=';')
Writing to a file (2d)
save -ascii data.txt f save('data.csv', f,
fmt='%.6f', delimiter=';')
f.tofile(file='data.csv', Writing to a file (1d)
format='%.6f', sep=';')
Reading from a file (1d)
f=
fromfile(file='data.csv',
sep=';')
f = load('data.txt')
MATLAB/Octave
Python
a = [ 11 12 13 14 ... a = array([[ 11, 12, 13,
21 22 23 24 ...
14 ],
31 32 33 34 ]
[ 21, 22, 23, 24 ],
[ 31, 32, 33, 34 ]])
a(2,3)
a[1,2]
a(1,:)
a[0,]
a(:,1)
a[:,0]
a([1 3],[1 4]);
a.take([0,2]).take([0,3],
axis=1)
a(2:end,:)
a[1:,]
a(end-1:end,:)
a[-2:,]
a(1:2:end,:)
a[::2,:]
a[...,2]
a(:,[1 3 4])
a.take([0,2,3],axis=1)
a.diagonal(offset=0)
Description
Input is a 3,4 array
Element 2,3 (row,col)
First row
First column
Array as indices
All, except first row
Last two rows
Strides: Every other row
Third in last dimension (axis)
Remove one column
Diagonal
Assignment
MATLAB/Octave
Python
a(:,1) = 99
a(:,1) = [99 98 97]'
a[:,0] = 99
a[:,0] =
array([99,98,97])
Clipping: Replace all elements
(a>90).choose(a,90)
a.clip(min=None, max=90) over 90
Clip upper and lower values
a.clip(min=2, max=5)
a(a>90) = 90;
Description
Transpose and inverse
MATLAB/Octave
Python
Description
a'
a.' or transpose(a)
det(a)
inv(a)
pinv(a)
norm(a)
eig(a)
svd(a)
chol(a)
[v,l] = eig(a)
rank(a)
a.conj().transpose()
a.transpose()
linalg.det(a) or
linalg.inv(a) or
linalg.pinv(a)
norm(a)
linalg.eig(a)[0]
linalg.svd(a)
linalg.cholesky(a)
linalg.eig(a)[1]
rank(a)
Transpose
Non­conjugate transpose
Determinant
Inverse
Pseudo­inverse
Norms
Eigenvalues
Singular values
Cholesky factorization
Eigenvectors
Rank
Sum
Equivalents to "size"
MATLAB/Octave
Python
Description
MATLAB/Octave
Python
Description
sum(a)
sum(a')
sum(sum(a))
a.sum(axis=0)
a.sum(axis=1)
a.sum()
a.trace(offset=0)
a.cumsum(axis=0)
Sum of each column
Sum of each row
Sum of all elements
Sum along diagonal
Cumulative sum (columns)
size(a)
size(a,2) or length(a)
a.shape or a.getshape()
a.shape[1] or size(a,
axis=1)
a.size or size(a[,
axis=None])
a.ndim
a.nbytes
Matrix dimensions
Number of columns
cumsum(a)
length(a(:))
ndims(a)
Sorting
MATLAB/Octave
Python
Description
a = [ 4 3 2 ; 2 8 6 ; 1a = array([[4,3,2],
47]
[2,8,6],[1,4,7]])
sort(a(:))
a.ravel().sort() or
sort(a)
a.sort(axis=0) or msort(a)
sort(a')'
a.sort(axis=1)
sortrows(a,1)
a[a[:,0].argsort(),]
a.ravel().argsort()
a.argsort(axis=0)
a.argsort(axis=1)
Example data
Flat and sorted
Sort each column
Sort each row
Sort rows (by first row)
Sort, return indices
Sort each column, return indices
Sort each row, return indices
MATLAB/Octave
Python
Description
a .* b
a*b
a * b or multiply(a,b)
matrixmultiply(a,b)
inner(a,b) or
Elementwise operations
Matrix product (dot product)
Inner matrix vector multiplication
$a\cdot b'$
Outer product
Kronecker product
Matrix division,
$b{\cdot}a^{­1}$
Left matrix division, $b^{­1}
{\cdot}a$ \newline (solve linear
equations)
Vector dot product
Cross product
kron(a,b)
a/b
outer(a,b) or
kron(a,b)
linalg.solve(a,b)
Maximum and minimum
Python
Description
max(a)
a.max(0) or amax(a
[,axis=0])
a.max(1) or amax(a,
axis=1)
a.max() or
max in each column
max(a')
max(max(a))
[v i] = max(a)
max(b,c)
cummax(a)
Number of dimensions
Number of bytes used in memory
Matrix­ and elementwise­ multiplication
a\b
MATLAB/Octave
Number of elements
vdot(a,b)
cross(a,b)
max in each row
maximum(b,c)
max in array
return indices, i
pairwise max
a.ptp(); a.ptp(0)
max­to­min range
Matrix manipulation
MATLAB/Octave
Python
Description
fliplr(a)
flipud(a)
rot90(a)
repmat(a,2,3)
kron(ones(2,3),a)
triu(a)
tril(a)
fliplr(a) or a[:,::-1]
flipud(a) or a[::-1,]
rot90(a)
kron(ones((2,3)),a)
Flip left­right
Flip up­down
Rotate 90 degrees
Repeat matrix: [ a a a ; a a a ]
triu(a)
tril(a)
Triangular, upper
Triangular, lower
Find; conditional indexing
MATLAB/Octave
Python
Description
find(a)
[i j] = find(a)
a.ravel().nonzero()
(i,j) = a.nonzero()
(i,j) = where(a!=0)
v=
a.compress((a!=0).flat)
v = extract(a!=0,a)
(a>5.5).nonzero()
a.compress((a>5.5).flat)
where(a>5.5,0,a) or a *
(a>5.5)
a.put(2,indices)
Non­zero elements, indices
Non­zero elements, array
indices
Vector of non­zero values
[i j v] = find(a)
find(a>5.5)
a .* (a>5.5)
Condition, indices
Return values
Zero out elements above 5.5
Replace values
Related documents