This document is a reverse and updated version of "NumPy for MATLAB users" thesaurus written by Vidar Bronken Gundersen / Mathesaurus in 2006, and also inspired from another MATLAB/NumPy cross-reference by Numpy developers. Here the GNU Octave commands have been completed, fixed, and sometimes replaced by correct or more appropriate functions, as used by a real MATLAB/Octave programmer.
In the tables below, for Python commands it is assumed that you have imported some libraries as follows:
import numpy as np
import math
import matplotlib.pyplot as plt
Also, we present here only the functional form of expressions, but most of Python commands have their strict equivalent using an object-oriented form, i.e., the method. Example: a.size is similar to np.size(a). Note that the method name may be different than the function name.
Expressions in red are specific to GNU Octave, i.e., not MATLAB compatible.
Python | Octave | Description |
---|---|---|
help() | doc | Browse help interactively |
help help doc doc | Help on using help | |
help(plt.plot) | help plot doc plot | Help for a function |
help(np) | doc splines | Help for a toolbox/library package |
demo | Demonstration examples |
Python | Octave | Description |
---|---|---|
lookfor plot | Search keyword in help files | |
help(); modules [Numeric] | help | List available packages |
help(plt.plot) | which plot | Locate functions |
Python | Octave | Description |
---|---|---|
ipython -pylab | octave -q | Start session |
TAB | TAB | Auto completion |
execfile('foo.py') run foo.py | foo foo.m | Run code from file |
hist -n | history | Command history |
diary on [..] diary off | Save command history | |
CTRL-D CTRL-Z # windows sys.exit() | exit quit | End session |
Python | Octave | Description |
---|---|---|
help - | Help on operator syntax |
Python | Octave | Description |
---|---|---|
a=1; b=2 | a=1; b=2; | Assignment; defining a number |
a + b add(a,b) | a + b plus(a,b) | Addition |
a - b subtract(a,b) | a - b minus(a,b) | Subtraction |
a * b multiply(a,b) | a .* b times(a,b) | Multiplication |
a / b divide(a,b) | a ./ b rdivide(a,b) | Right division |
b / a | a .\ b ldivide(a,b) | Left division |
a ** b np.power(a,b) math.pow(a,b) | a .^ b power(a,b) | Power, ab |
np.remainder(a,b) | rem(a,b) | Remainder after division |
a % b np.fmod(a,b) math.fmod(a,b) | mod(a,b) | Modulo |
a+=b add(a,b,a) | a+=b plus(a,b,a) | In place operation to save array creation overhead |
math.factorial(a) | factorial(a) | Factorial, n! |
Python | Octave | Description |
---|---|---|
a == b equal(a,b) | a == b eq(a,b) | Equal |
a < b less(a,b) | a < b lt(a,b) | Less than |
a > b greater(a,b) | a > b gt(a,b) | Greater than |
a <= b less_equal(a,b) | a <= b le(a,b) | Less than or equal |
a >= b greater_equal(a,b) | a >= b ge(a,b) | Greater than or equal |
a != b not_equal(a,b) | a ~= b a != b ne(a,b) | Not Equal |
Python | Octave | Description |
---|---|---|
a and b | a && b | Short-circuit logical AND |
a or b | a || b | Short-circuit logical OR |
logical_and(a,b) a and b | a & b and(a,b) | Element-wise logical AND |
logical_or(a,b) a or b | a | b or(a,b) | Element-wise logical OR |
logical_xor(a,b) | xor(a, b) | Logical EXCLUSIVE OR |
logical_not(a) not a | ~a not(a) !a | Logical NOT |
any(a) | True if any element is nonzero | |
all(a) | True if all elements are nonzero |
Python | Octave | Description |
---|---|---|
math.sqrt(a) | sqrt(a) | Square root |
math.log(a) | log(a) | Logarithm, base e (natural) |
math.log10(a) | log10(a) | Logarithm, base 10 |
math.log(a, 2) | log2(a) | Logarithm, base 2 (binary) |
math.exp(a) | exp(a) | Exponential function |
Python | Octave | Description |
---|---|---|
np.around(a) | round(a) | Round |
np.ceil(a) | ceil(a) | Round up |
np.floor(a) | floor(a) | Round down |
np.fix(a) | fix(a) | Round towards zero |
Python | Octave | Description |
---|---|---|
math.pi | pi | π=3.141592 |
math.e math.exp(1) | exp(1) | e=2.718281 |
Python | Octave | Description |
---|---|---|
nan | NaN | Not a Number |
inf | Inf | Infinity, ∞ |
plus_inf | +Inf | Infinity, +∞ |
minus_inf | -Inf | Infinity, -∞ |
plus_zero | Plus zero, +0 | |
minus_zero | Minus zero, -0 |
Python | Octave | Description |
---|---|---|
1j | i,j,1i,1j | Imaginary unit |
3 + 4j complex(3,4) | 3 + 4i complex(3,4) | A complex number, 3+4i |
abs(z) | abs(z) | Absolute value (modulus) |
no.real(z) | real(z) | Real part |
np.imag(z) | imag(z) | Imaginary part |
np.angle(z) | arg(z) | Argument |
np.conj(z) | conj(z) | Complex conjugate |
Python | Octave | Description |
---|---|---|
math.atan2(b,a) | atan2(b,a) | Arctangent, arctan(b/a) |
hypot(x,y) | Hypotenus; Euclidean distance |
Python | Octave | Description |
---|---|---|
np.random.random((10,)) np.random.uniform((10,)) | rand(1,10) | Uniform distribution |
np.random.uniform(2,7,(10,)) | 2+5*rand(1,10) | Uniform: Numbers between 2 and 7 |
np.random.uniform(0,1,(6,6)) | rand(6) | Uniform: 6,6 array |
np.random.standard_normal((10,)) | randn(1,10) | Normal distribution |
Python | Octave | Description |
---|---|---|
a=np.array([2,3,4,5]) | a=[2 3 4 5]; | Row vector, 1×n-matrix |
np.array([2,3,4,5])[:,NewAxis] np.array([2,3,4,5]).reshape(-1,1) r_[1:10,'c'] | adash=[2 3 4 5]'; | Column vector, m×1-matrix |
Python | Octave | Description |
---|---|---|
np.arange(1,11, dtype=Float) range(1,11) | 1:10 | 1,2,3, ... ,10 |
np.arange(10.) | 0:9 | 0.0,1.0,2.0, ... ,9.0 |
np.arange(1,11,3) | 1:3:10 | 1,4,7,10 |
np.arange(10,0,-1) | 10:-1:1 | 10,9,8, ... ,1 |
arange(10,0,-3) | 10:-3:1 | 10,7,4,1 |
np.linspace(1,10,7) | linspace(1,10,7) | Linearly spaced vector of n=7 points |
a[::-1] | flip(a) | Reverse |
a[:] = 3 | a(:) = 3 | Set all values to same scalar value |
Python | Octave | Description |
---|---|---|
np.concatenate((a,a)) | [a a] cat(2,a,a) | Concatenate two vectors |
np.concatenate((range(1,5),a), axis=1) | [1:4 a] |
Python | Octave | Description |
---|---|---|
np.concatenate((a,a)) | repmat(a,1,2) | 1 2 3 1 2 3 |
np.repeat(a,3) | repelem(a,3) repmat(a,1,3)(:)' | 1 1 1 2 2 2 3 3 3 |
np.repeat(a,a) | repelem(a,a) | 1 2 2 3 3 3 |
Python | Octave | Description |
---|---|---|
a[1:] | a(2:end) | miss the first element |
a([1:9]) | miss the tenth element | |
a[-1] | a(end) | last element |
a[-2:] | a(end-1:end) | last two elements |
Python | Octave | Description |
---|---|---|
np.maximum(a,b) | max(a,b) | pairwise max |
np.concatenate((a,b)).max() | max([a b]) | max of all values in two vectors |
v,i = a.max(0),a.argmax(0) | [v,i] = max(a) |
Python | Octave | Description |
---|---|---|
a*a | a.*a | Multiply two vectors |
dot(u,v) | dot(u,v) | Vector dot product, u · v |
Python | Octave | Description |
---|---|---|
a = array([[2,3],[4,5]]) | a = [2 3;4 5] | Define a matrix |
Python | Octave | Description |
---|---|---|
np.concatenate((a,b), axis=0) np.vstack((a,b)) | [a;b] cat(1,a,b) | Bind rows |
np.concatenate((a,b), axis=1) np.hstack((a,b)) | [a,b] cat(2,a,b) | Bind columns |
np.concatenate((a,b), axis=2) np.dstack((a,b)) | cat(3,a,b) | Bind slices (three-way arrays) |
np.concatenate((a,b), axis=None) | [a(:), b(:)] | Concatenate matrices into one vector |
np.concatenate((r_[1:5],r_[1:5])).reshape(2,-1) np.vstack((r_[1:5],r_[1:5])) | [1:4 ; 1:4] | Bind rows (from vectors) |
[1:4 ; 1:4]' | Bind columns (from vectors) |
Python | Octave | Description |
---|---|---|
np.zeros((3,5)) | zeros(3,5) | 0 filled array |
np.zeros((3,5),np.int8) | zeros(3,5,'int8') int8(zeros(3,5)) | 0 filled array of 8-bit integers |
np.ones((3,5)) | ones(3,5) | 1 filled array |
ones(3,5)*9 | Any number filled array | |
np.identity(3) | eye(3) | Identity matrix |
np.diag((4,5,6)) | diag([4 5 6]) | Diagonal |
magic(3) | Magic squares; Lo Shu | |
a = np.empty((3,3)) | Empty array |
Python | Octave | Description |
---|---|---|
np.arange(1,7).reshape(2,-1) a.setshape(2,3) | reshape(1:6,3,2)' | Reshaping (rows first) |
np.arange(1,7).reshape(-1,2).transpose() | reshape(1:6,2,3) | Reshaping (columns first) |
np.ravel(a) | a'(:) a = a'; a(:) | Flatten to vector (by rows, like comics) |
np.ravel(a, order='F') | a(:) | Flatten to vector (by columns) |
vech(a) | Flatten upper triangle (by columns) |
Python | Octave | Description |
---|---|---|
b = a | Reference to a (alias) | |
b = a.copy() | b = a; | Copy of a |
Python | Octave | Description |
---|---|---|
a = array([[ 11, 12, 13, 14 ], [ 21, 22, 23, 24 ], [ 31, 32, 33, 34 ]]) | a = [11 12 13 14; 21 22 23 24; 31 32 33 34]; | Input is a 3x4 array |
a[1,2] | a(2,3) | Element 2,3 (row,col) |
a[0,] | a(1,:) | First row |
a[:,0] | a(:,1) | First column |
a.take([0,2]).take([0,3], axis=1) | a([1 3],[1 4]); | Array as indices |
a[1:,] | a(2:end,:) | All, except first row |
a[-2:,] | a(end-1:end,:) | Last two rows |
a[::2,:] | a(1:2:end,:) | Strides: Every other row |
a[...,2] | Third in last dimension (axis) | |
a.take([0,2,3],axis=1) | a(:,[1 3 4]) | Remove one column |
a.diagonal(offset=0) | Diagonal |
Python | Octave | Description |
---|---|---|
a[:,0] = 99 | a(:,1) = 99; | |
a[:,0] = array([99,98,97]) | a(:,1) = [99;98;97]; | |
(a>90).choose(a,90) a.clip(min=None, max=90) | a(a>90) = 90; | Clipping: Replace all elements over 90 |
a.clip(min=2, max=5) | a(a<2) = 2; a(a>5) = 5; | Clip upper and lower values |
Python | Octave | Description |
---|---|---|
a.conj().transpose() | a' | Transpose |
np.transpose(a) | a.' transpose(a) | Non-conjugate transpose |
np.linalg.det(a) | det(a) | Determinant |
np.linalg.inv(a) | inv(a) | Inverse |
np.linalg.pinv(a) | pinv(a) | Pseudo-inverse |
norm(a) | norm(a) | Norms |
np.linalg.eig(a)[0] | eig(a) | Eigenvalues |
np.linalg.svd(a) | svd(a) | Singular values |
np.linalg.cholesky(a) | chol(a) | Cholesky factorization |
np.linalg.eig(a)[1] | [v,l] = eig(a) | Eigenvectors |
np.rank(a) | rank(a) | Rank |
Python | Octave | Description |
---|---|---|
sum(a) | sum(a) | Sum of each column |
np.sum(a,axis=1) | sum(a,2) | Sum of each row |
np.sum(a) | sum(a(:)) | Sum of all elements |
np.trace(a) | trace(a) | Sum along diagonal |
np.cumsum(a) | cumsum(a'(:)) | Cumulative sum of all values (by rows) |
np.cumsum(a,axis=0) | cumsum(a) | Cumulative sum (each columns) |
Python | Octave | Description |
---|---|---|
a = array([[4,3,2],[2,8,6],[1,4,7]]) | a = [4,3,2;2,8,6;1,4,7]; | Example data |
a.ravel().sort() | sort(a(:)) | Flat and sorted |
a.sort(axis=0) msort(a) | sort(a) | Sort each column |
a.sort(axis=1) | sort(a,2) | Sort each row |
a[a[:,0].argsort(),] | sortrows(a,1) | Sort rows (by first row) |
a.ravel().argsort() | [~,k]=sort(a) | Sort, return indices |
a.argsort(axis=0) | [~,k]=sort(a,1) | Sort each column, return indices |
a.argsort(axis=1) | [~,k]=sort(a,2) | Sort each row, return indices |
Python | Octave | Description |
---|---|---|
a.max(0) np.amax(a [,axis=0]) | max(a) | max in each column |
a.max(1) np.amax(a, axis=1) | max(a') max(a,[],2) | max in each row |
a.max() | max(a(:)) | max in array |
[v,i] = max(a) | return indices, i | |
np.maximum(b,c) | max(b,c) | pairwise max |
a.ptp() | max(a(:)) - min(a(:)) | max-to-min range |
Python | Octave | Description |
---|---|---|
np.fliplr(a) a[:,::-1] | fliplr(a) | Flip left-right |
np.flipud(a) a[::-1,] | flipud(a) | Flip up-down |
np.rot90(a) | rot90(a) | Rotate 90 degrees |
kron(ones((2,3)),a) | repmat(a,2,3) kron(ones(2,3),a) | Repeat matrix: [ a a a ; a a a ] |
np.triu(a) | triu(a) | Triangular, upper |
np.tril(a) | tril(a) | Triangular, lower |
Python | Octave | Description |
---|---|---|
a.shape a.getshape() | size(a) | Matrix dimensions |
a.shape[1] size(a, axis=1) | size(a,2) | Number of columns |
a.size size(a[, axis=None]) | numel(a) length(a(:)) | Total number of elements |
max(a.shape) | length(a) | Number of elements along the largest dimension |
a.ndim | ndims(a) | Number of dimensions |
a.nbytes | x = whos('a'); x.bytes | Number of bytes used in memory |
Python | Octave | Description |
---|---|---|
a * b np.multiply(a,b) | a .* b times(a,b) | Elementwise operations |
np.matrixmultiply(a,b) | a * b mtimes(a,b) | Matrix product (dot product) |
np.inner(a,b) | Inner matrix vector multiplication a · b' | |
np.outer(a,b) | Outer product | |
kron(a,b) | kron(a,b) | Kronecker product |
a / b | Matrix division, b · a-1 | |
np.linalg.solve(a,b) | a \ b | Left matrix division, b-1 · a (solve linear equations) |
np.vdot(a,b) | Vector dot product | |
np.cross(a,b) | Cross product |
Python | Octave | Description |
---|---|---|
a.ravel().nonzero() | find(a) | Non-zero elements, indices |
(i,j) = a.nonzero() (i,j) = where(a!=0) | [i j] = find(a) | Non-zero elements, array indices |
v = a.compress((a!=0).flat) v = extract(a!=0,a) | [i j v] = find(a) | Vector of non-zero values |
(a>5.5).nonzero() | find(a>5.5) | Condition, indices |
a.compress((a>5.5).flat) | Return values | |
np.where(a>5.5,0,a) a * (a>5.5) | a .* (a>5.5) | Zero out elements above 5.5 |
a.put(2,indices) | Replace values |
Python | Octave | Description |
---|---|---|
a = array([[[1,2],[1,2]], [[3,4],[3,4]]]) | a = cat(3, [1 2; 1 2],[3 4; 3 4]); | Define a 3-way array |
a[0,...] | a(1,:,:) |
Python | Octave | Description |
---|---|---|
f = np.fromfile("data.txt") f = load("data.txt"); | f = load('data.txt') | Reading from a file (2d) |
f = load('data.csv', delimiter=';') | x = dlmread('data.csv', ';'); | Reading fram a CSV file (2d) |
save('data.csv', f, fmt='%.6f', delimiter=';') | save -ascii data.txt f | Writing to a file (2d) |
f.tofile(file='data.csv', format='%.6f', sep=';') | Writing to a file (1d) | |
f = np.fromfile(file='data.csv', sep=';') | Reading from a file (1d) |
Python | Octave | Description |
---|---|---|
plot(a) | plot(a) | 1d line plot |
plot(x[:,0],x[:,1],'o') | plot(x(:,1),x(:,2),'o') | 2d scatter plot |
plot(x1,y1,'bo', x2,y2,'go') | plot(x1,y1, x2,y2) | Two graphs in one plot |
plot(x1,y1,'o') plot(x2,y2,'o') show() # as normal | plot(x1,y1) hold on plot(x2,y2) | Overplotting: Add new plots to current |
subplot(211) | subplot(211) | subplots |
plot(x,y,'ro-') | plot(x,y,'ro-') | Plotting symbols and color |
Python | Octave | Description |
---|---|---|
grid() | grid on | Turn on grid lines |
figure(figsize=(6,6)) | axis equal | 1:1 aspect ratio |
axis([ 0, 10, 0, 5 ]) | axis([ 0 10 0 5 ]) | Set axes manually |
title('title') xlabel('x-axis') ylabel('y-axis') | Axis labels and titles | |
text(2,25,'hello') | Insert text |
Python | Octave | Description |
---|---|---|
semilogy(a) | semilogy(a) | logarithmic y-axis |
semilogx(a) | semilogx(a) | logarithmic x-axis |
loglog(a) | loglog(a) | logarithmic x and y axes |
Python | Octave | Description |
---|---|---|
fill(t,s,'b', t,c,'g', alpha=0.2) | fill(t,s,'b', t,c,'g') | Filled plot |
Python | Octave | Description |
---|---|---|
f = @(x) sin(x/3) - cos(x/5) | Defining functions | |
x = arrayrange(0,40,.5) y = sin(x/3) - cos(x/5) plot(x,y, 'o') | fplot(f,[0,40]) ezplot('sin(x/3) - cos(x/5)',[0,40]) | Plot a function for given range |
Python | Octave | Description |
---|---|---|
theta = arange(0,2*pi,0.001) rho = sin(2*theta) | theta = 0:.001:2*pi; rho = sin(2*theta); | |
polar(theta, rho) | polar(theta, rho) |
Python | Octave | Description |
---|---|---|
hist(randn(1000,1)) | ||
hist(randn(1000,1), -4:4) | ||
plot(sort(a)) |
Python | Octave | Description |
---|---|---|
levels, colls = contour(Z, V, origin='lower', extent=(-3,3,-3,3)) clabel(colls, levels, inline=1, fmt='%1.1f', fontsize=10) | contour(z) | Contour plot |
contourf(Z, V, cmap=cm.gray, origin='lower', extent=(-3,3,-3,3)) | contourf(z); colormap(gray) | Filled contour plot |
im = imshow(Z, interpolation='bilinear', origin='lower', extent=(-3,3,-3,3)) | image(z) colormap(gray) | Plot image data |
# imshow() and contour() as above | Image with contours | |
quiver() | quiver() | Direction field vectors |
Python | Octave | Description |
---|---|---|
n=arrayrange(-2,2,.1) [x,y] = meshgrid(n,n) z = x*power(math.e,-x**2-y**2) | n=-2:.1:2; [x,y] = meshgrid(n,n); z=x.*exp(-x.^2-y.^2); | |
mesh(z) | Mesh plot | |
surf(x,y,z) surfl(x,y,z) | Surface plot |
Python | Octave | Description |
---|---|---|
plot3(x,y,z,'k+') | 3d scatter plot |
Python | Octave | Description |
---|---|---|
savefig('foo.eps') | print('-depsc','foo.eps') | PostScript |
savefig('foo.pdf') | print('-dpdf','foo.pdf') | |
savefig('foo.svg') | print('-dsvg','foo.svg') | SVG (vector graphics for www) |
savefig('foo.png') | print('-dpng','foo.png') | PNG (raster graphics) |
savefig('foo.fig') | Reloadable graphics object |
Python | Octave | Description |
---|---|---|
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 = [1,2,2,5,2]; b = [2,3,4]; | Create sets |
np.unique1d(a) np.unique(a) set(a) | unique(a) | Set unique |
np.union1d(a,b) | union(a,b) | Set union |
np.intersect1d(a) | intersect(a,b) | Set intersection |
np.setdiff1d(a,b) | setdiff(a,b) | Set difference |
np.setxor1d(a,b) | setxor(a,b) | Set exclusion |
2 in a np.setmember1d(2,a) contains(a,2) | ismember(2,a) | True for set member |
Python | Octave | Description |
---|---|---|
a.mean(axis=0) mean(a [,axis=0]) | mean(a) | Average |
median(a) median(a [,axis=0]) | median(a) | Median |
np.std(a) | std(a(:)) | Standard deviation |
np.var(a) var(a) | var(a(:)) | Variance |
np.correlate(x,y) corrcoef(x,y) | corr(x,y) | Correlation coefficient |
np.cov(x,y) | cov(x,y) | Covariance |
Python | Octave | Description |
---|---|---|
(a,b) = polyfit(x,y,1) plot(x,y,'o', x,a*x+b,'-') | p = polyfit(x,y,1); plot(x,y,'o',x,polyval(p,x),'-') | Straight line fit |
np.linalg.lstsq(x,y) | a = x\y | Linear least squares y = ax + b |
np.polyfit(x,y,3) | polyfit(x,y,3) | Polynomial fit |
Python | Octave | Description |
---|---|---|
np.poly() | poly(x) | Polynomial |
np.roots() | roots([1 -1 -1]) | Find zeros of polynomial |
f = @(x) 1/x - (x-1); fzero(f,1) | Find a zero near x = 1 | |
solve('1/x = x-1') | Solve symbolic equations | |
polyval(array([1,2,1,2]),arange(1,11)) | polyval([1 2 1 2],1:10) | Evaluate polynomial |
Python | Octave | Description |
---|---|---|
np.diff(x, n=1, axis=0) | diff(x) | Discrete difference function and approximate derivative |
integrate.solve_ivp(f) | ode45(f) | Solve differential equations |
Python | Octave | Description |
---|---|---|
np.fft(a) | fft(a) | Fast fourier transform |
np.ifft(a) | ifft(a) | Inverse fourier transform |
np.convolve(x,y) | conv(x,y) | Linear convolution |
Python | Octave | Description |
---|---|---|
factor() | Factorization |
Python | Octave | Description |
---|---|---|
.py | .m | Script file extension |
# | % # | Comment symbol (rest of line) |
from pylab import * | % must be in current directory or MATLABPATH % must be in current directory or LOADPATH | Import library functions |
string="a=234" eval(string) | string='a=234'; eval(string) | Eval |
Python | Octave | Description |
---|---|---|
for i in range(1,6): print(i) | for i=1:5, disp(i), end | for-statement |
for i in range(1,6): print(i) print(i*2) | for i=1:5 disp(i) disp(i*2) end | Multiline for statements |
Python | Octave | Description |
---|---|---|
if 1>0: a=100 | if 1>0 a=100; end | if-statement |
if 1>0 a=100; else a=0; end | if-else-statement |
Python | Octave | Description |
---|---|---|
ans | Most recent evaluated expression | |
whos who | List variables loaded into memory | |
clear x clear [all] | Clear variable x from memory | |
a print(a) | a disp(a) | Display variable content |
pdb.set_trace() breakpoint() | keyboard | Insert a break for manual debugging |
pdb.pm() | dbstop if error | Will break for debugging at error |
Python | Octave | Description |
---|---|---|
os.listdir(".") | dir ls | List files in directory |
what | List script or environment files in directory | |
os.getcwd() | pwd | Displays the current working directory |
os.chdir('foo') | cd foo | Change working directory |
os.system('notepad') os.popen('notepad') | system('notepad') | Invoke a System Command |
Time-stamp: "2022-09-13T17:00:00 beauducel"
© 2006 Vidar Bronken Gundersen, /mathesaurus.sf.net
© 2022 François Beauducel / IPGP
Permission is granted to copy, distribute and/or modify this document as long as the above attribution is retained.