GNU Octave logo GNU Octave for Python/NumPy users

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.

Help

PythonOctaveDescription
help()docBrowse help interactively
help help
doc doc
Help on using help
help(plt.plot)help plot
doc plot
Help for a function
help(np)doc splinesHelp for a toolbox/library package
demoDemonstration examples

Searching available documentation

PythonOctaveDescription
lookfor plotSearch keyword in help files
help(); modules [Numeric]helpList available packages
help(plt.plot)which plotLocate functions

Using interactively

PythonOctaveDescription
ipython -pylaboctave -qStart session
TABTABAuto completion
execfile('foo.py')
run foo.py
foo
foo.m
Run code from file
hist -nhistoryCommand history
diary on [..] diary offSave command history
CTRL-D
CTRL-Z # windows
sys.exit()
exit
quit
End session

Operators

PythonOctaveDescription
help -Help on operator syntax

Arithmetic operators

PythonOctaveDescription
a=1; b=2a=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 / aa .\ 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!

Relational operators

PythonOctaveDescription
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

Logical operators

PythonOctaveDescription
a and ba && bShort-circuit logical AND
a or ba || bShort-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

root and logarithm

PythonOctaveDescription
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

Round off

PythonOctaveDescription
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

Mathematical constants

PythonOctaveDescription
math.pipiπ=3.141592
math.e
math.exp(1)
exp(1)e=2.718281

Missing values; IEEE-754 floating point status flags

PythonOctaveDescription
nanNaNNot a Number
infInfInfinity, ∞
plus_inf+InfInfinity, +∞
minus_inf-InfInfinity, -∞
plus_zeroPlus zero, +0
minus_zeroMinus zero, -0

Complex numbers

PythonOctaveDescription
1ji,j,1i,1jImaginary 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

Trigonometry

PythonOctaveDescription
math.atan2(b,a)atan2(b,a)Arctangent, arctan(b/a)
hypot(x,y)Hypotenus; Euclidean distance

Generate random numbers

PythonOctaveDescription
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

Vectors

PythonOctaveDescription
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

Sequences

PythonOctaveDescription
np.arange(1,11, dtype=Float)
range(1,11)
1:101,2,3, ... ,10
np.arange(10.)0:90.0,1.0,2.0, ... ,9.0
np.arange(1,11,3)1:3:101,4,7,10
np.arange(10,0,-1)10:-1:110,9,8, ... ,1
arange(10,0,-3)10:-3:110,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[:] = 3a(:) = 3Set all values to same scalar value

Concatenation (vectors)

PythonOctaveDescription
np.concatenate((a,a))[a a]
cat(2,a,a)
Concatenate two vectors
np.concatenate((range(1,5),a), axis=1)[1:4 a]

Repeating

PythonOctaveDescription
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

Miss those elements out

PythonOctaveDescription
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

Maximum and minimum

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

Vector multiplication

PythonOctaveDescription
a*aa.*aMultiply two vectors
dot(u,v)dot(u,v)Vector dot product, u · v

Matrices

PythonOctaveDescription
a = array([[2,3],[4,5]])a = [2 3;4 5]Define a matrix

Concatenation (matrices); rbind and cbind

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

Array creation

PythonOctaveDescription
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)*9Any 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

Reshape and flatten matrices

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

Shared data (slicing)

PythonOctaveDescription
b = aReference to a (alias)
b = a.copy()b = a;Copy of a

Indexing and accessing elements (Python: slicing)

PythonOctaveDescription
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

Assignment

PythonOctaveDescription
a[:,0] = 99a(:,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

Transpose and inverse

PythonOctaveDescription
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

Sum

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

Sorting

PythonOctaveDescription
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

Maximum and minimum

PythonOctaveDescription
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

Matrix manipulation

PythonOctaveDescription
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

Matrix shape and size

PythonOctaveDescription
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.ndimndims(a)Number of dimensions
a.nbytesx = whos('a'); x.bytesNumber of bytes used in memory

Matrix - and elementwise - multiplication

PythonOctaveDescription
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 / bMatrix division, b · a-1
np.linalg.solve(a,b)
a \ bLeft matrix division, b-1 · a
(solve linear equations)
np.vdot(a,b)Vector dot product
np.cross(a,b)Cross product

Find; conditional indexing

PythonOctaveDescription
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

Multi-way arrays

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

File input and output

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

Plotting

Basic x-y plots

PythonOctaveDescription
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

Axes and titles

PythonOctaveDescription
grid()grid onTurn on grid lines
figure(figsize=(6,6))axis equal1: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

Log plots

PythonOctaveDescription
semilogy(a)semilogy(a)logarithmic y-axis
semilogx(a)semilogx(a)logarithmic x-axis
loglog(a)loglog(a)logarithmic x and y axes

Filled plots and bar plots

PythonOctaveDescription
fill(t,s,'b', t,c,'g', alpha=0.2)fill(t,s,'b', t,c,'g')Filled plot

Functions

PythonOctaveDescription
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

Polar plots

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

Histogram plots

PythonOctaveDescription
hist(randn(1000,1))
hist(randn(1000,1), -4:4)
plot(sort(a))

3d data

Contour and image plots

PythonOctaveDescription
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 aboveImage with contours
quiver()quiver()Direction field vectors

Perspective plots of surfaces over the x-y plane

PythonOctaveDescription
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

Scatter (cloud) plots

PythonOctaveDescription
plot3(x,y,z,'k+')3d scatter plot

Save plot to a graphics file

PythonOctaveDescription
savefig('foo.eps')print('-depsc','foo.eps')PostScript
savefig('foo.pdf')print('-dpdf','foo.pdf')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

Data analysis

Set membership operators

PythonOctaveDescription
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

Statistics

PythonOctaveDescription
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

Interpolation and regression

PythonOctaveDescription
(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\yLinear least squares y = ax + b
np.polyfit(x,y,3)polyfit(x,y,3)Polynomial fit

Non-linear methods

Polynomials, root finding

PythonOctaveDescription
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

Differential equations

PythonOctaveDescription
np.diff(x, n=1, axis=0)diff(x)Discrete difference function and approximate derivative
integrate.solve_ivp(f)ode45(f)Solve differential equations

Fourier analysis

PythonOctaveDescription
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

Symbolic algebra, calculus

PythonOctaveDescription
factor()Factorization

Programming

PythonOctaveDescription
.py.mScript 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

Loops

PythonOctaveDescription
for i in range(1,6): print(i)for i=1:5, disp(i), endfor-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

Conditionals

PythonOctaveDescription
if 1>0: a=100if 1>0 a=100; endif-statement
if 1>0 a=100; else a=0; endif-else-statement

Debugging

PythonOctaveDescription
ansMost 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()
keyboardInsert a break for manual debugging
pdb.pm()dbstop if errorWill break for debugging at error

Working directory and OS

PythonOctaveDescription
os.listdir(".")dir
ls
List files in directory
whatList script or environment files in directory
os.getcwd()pwdDisplays the current working directory
os.chdir('foo')cd fooChange 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.