NumPy for Matlab users

Introduction

MATLAB® and NumPy/SciPy have a lot in common. But there are many differences. NumPy and SciPy were created to do numerical and scientific computing in the most natural way with Python, not to be MATLAB® clones. This page is intended to be a place to collect wisdom about the differences, mostly for the purpose of helping proficient MATLAB® users become proficient NumPy and SciPy users.

Some Key Differences

MATLAB NumPy
In MATLAB®, the basic data type is a multidimensional array of double precision floating point numbers. Most expressions take such arrays and return such arrays. Operations on the 2-D instances of these arrays are designed to act more or less like matrix operations in linear algebra. n NumPy the basic type is a multidimensional array. Operations on these arrays in all dimensionalities including 2D are elementwise operations. However, there is a special matrix type for doing linear algebra, which is just a subclass of the array class. Operations on matrix-class arrays are linear algebra operations.
MATLAB® uses 1 (one) based indexing. The initial element of a sequence is found using a(1). See note INDEXING Python uses 0 (zero) based indexing. The initial element of a sequence is found using a[0].
MATLAB®’s scripting language was created for doing linear algebra. The syntax for basic matrix operations is nice and clean, but the API for adding GUIs and making full-fledged applications is more or less an afterthought. NumPy is based on Python, which was designed from the outset to be an excellent general-purpose programming language. While Matlab’s syntax for some array manipulations is more compact than NumPy’s, NumPy (by virtue of being an add-on to Python) can do many things that Matlab just cannot, for instance subclassing the main array type to do both array and matrix math cleanly.
In MATLAB®, arrays have pass-by-value semantics, with a lazy copy-on-write scheme to prevent actually creating copies until they are actually needed. Slice operations copy parts of the array. In NumPy arrays have pass-by-reference semantics. Slice operations are views into an array.

‘array’ or ‘matrix’? Which should I use?

Short answer

Use arrays.

They are the standard vector/matrix/tensor type of numpy. Many numpy functions return arrays, not matrices. There is a clear distinction between element-wise operations and linear algebra operations. You can have standard vectors or row/column vectors if you like. The only disadvantage of using the array type is that you will have to use dot instead of * to multiply (reduce) two tensors (scalar product, matrix vector multiplication etc.).

Long answer

NumPy contains both an array class and a matrix class. The array class is intended to be a general-purpose n-dimensional array for many kinds of numerical computing, while matrix is intended to facilitate linear algebra computations specifically. In practice there are only a handful of key differences between the two.

  • Operator *, dot(), and multiply():
    • For array, ‘*’ means element-wise multiplication, and the dot() function is used for matrix multiplication.
    • For matrix, ‘*’ means matrix multiplication, and the multiply() function is used for element-wise multiplication.
  • Handling of vectors (one-dimensional arrays)
    • For array, the vector shapes 1xN, Nx1, and N are all different things. Operations like A[:,1] return a one-dimensional array of shape N, not a two-dimensional array of shape Nx1. Transpose on a one-dimensional array does nothing.
    • For matrix, one-dimensional arrays are always upconverted to 1xN or Nx1 matrices (row or column vectors). A[:,1] returns a two-dimensional matrix of shape Nx1.
  • Handling of higher-dimensional arrays (ndim > 2) array objects can have number of dimensions > 2; matrix objects always have exactly two dimensions. Convenience attributes
    • array has a .T attribute, which returns the transpose of the data.
    • matrix also has .H, .I, and .A attributes, which return the conjugate transpose, inverse, and asarray() of the matrix, respectively.
  • Convenience constructor
    • The array constructor takes (nested) Python sequences as initializers. As in, array([[1,2,3],[4,5,6]]).
    • The matrix constructor additionally takes a convenient string initializer. As in matrix("[1 2 3; 4 5 6]").

There are pros and cons to using both:

  • array
    • :) You can treat one-dimensional arrays as either row or column vectors. dot(A,v) treats v as a column vector, while dot(v,A) treats v as a row vector. This can save you having to type a lot of transposes.
    • <:( Having to use the dot() function for matrix-multiply is messy – dot(dot(A,B),C) vs. ABC.
    • :) Element-wise multiplication is easy: A*B.
    • :) array is the “default” NumPy type, so it gets the most testing, and is the type most likely to be returned by 3rd party code that uses NumPy.
    • :) Is quite at home handling data of any number of dimensions.
    • :) Closer in semantics to tensor algebra, if you are familiar with that.
    • :) All operations (*, /, +, - etc.) are elementwise
  • matrix
    • :\ Behavior is more like that of MATLAB® matrices.
    • <:( Maximum of two-dimensional. To hold three-dimensional data you need array or perhaps a Python list of matrix.
    • <:( Minimum of two-dimensional. You cannot have vectors. They must be cast as single-column or single-row matrices.
    • <:( Since array is the default in NumPy, some functions may return an array even if you give them a matrix as an argument. This shouldn’t happen with NumPy functions (if it does it’s a bug), but 3rd party code based on NumPy may not honor type preservation like NumPy does.
    • :) A*B is matrix multiplication, so more convenient for linear algebra.
    • <:( Element-wise multiplication requires calling a function, multipy(A,B).
    • <:( The use of operator overloading is a bit illogical: * does not work elementwise but / does.

The array is thus much more advisable to use.

Facilities for Matrix Users

NumPy has some features that facilitate the use of the matrix type, which hopefully make things easier for Matlab converts.

  • A matlib module has been added that contains matrix versions of common array constructors like ones(), zeros(), empty(), eye(), rand(), repmat(), etc. Normally these functions return arrays, but the matlib versions return matrix objects.
  • mat has been changed to be a synonym for asmatrix, rather than matrix, thus making it a concise way to convert an array to a matrix without copying the data.
  • Some top-level functions have been removed. For example numpy.rand() now needs to be accessed as numpy.random.rand(). Or use the rand() from the matlib module. But the “numpythonic” way is to use numpy.random.random(), which takes a tuple for the shape, like other numpy functions.

Table of Rough MATLAB-NumPy Equivalents

The table below gives rough equivalents for some common MATLAB® expressions. These are not exact equivalents, but rather should be taken as hints to get you going in the right direction. For more detail read the built-in documentation on the NumPy functions.

Some care is necessary when writing functions that take arrays or matrices as arguments — if you are expecting an array and are given a matrix, or vice versa, then ‘*’ (multiplication) will give you unexpected results. You can convert back and forth between arrays and matrices using

  • asarray: always returns an object of type array
  • asmatrix or mat: always return an object of type matrix
  • asanyarray: always returns an array object or a subclass derived from it, depending on the input. For instance if you pass in a matrix it returns a matrix.

These functions all accept both arrays and matrices (among other things like Python lists), and thus are useful when writing functions that should accept any array-like object.


In [1]:
import numpy as np
import scipy.linalg as la

get the number of dimensions of an array

MATLAB Numpy
ndims(a) ndim(a) or a.ndim

In [2]:
a = np.array([[1,2,3], [4,5,6], [7,8,9]])
m = np.matrix([[1,2,3], [4,5,6]])
print('a=', a)
print(19*'-')
print('m=', m)
print(19*'-')
print('ndim(a) = ', np.ndim(a))
print('a.ndim = ', a.ndim)
print(19*'-')
print('np.ndim(m) = ', np.ndim(m))
print('m.ndim = ', m.ndim)


a= [[1 2 3]
 [4 5 6]
 [7 8 9]]
-------------------
m= [[1 2 3]
 [4 5 6]]
-------------------
ndim(a) =  2
a.ndim =  2
-------------------
np.ndim(m) =  2
m.ndim =  2

get the number of elements of an array

MATLAB Numpy
numel(a) size(a) or a.size

In [3]:
a = np.array([[1,2,3], [4,5,6], [7,8,9]])
m = np.matrix([[1,2,3], [4,5,6]])
print('a=', a)
print(19*'-')
print('m=', m)
print(19*'-')
print('size(a) = ', np.size(a))
print('a.size = ', a.size)
print(19*'-')
print('np.size(m) = ', np.size(m))
print('m.size = ', m.size)


a= [[1 2 3]
 [4 5 6]
 [7 8 9]]
-------------------
m= [[1 2 3]
 [4 5 6]]
-------------------
size(a) =  9
a.size =  9
-------------------
np.size(m) =  6
m.size =  6

get the “size” of the matrix

MATLAB Numpy
size(a) shape(a) or a.shape

In [4]:
a = np.array([[1,2,3], [4,5,6], [7,8,9]])
m = np.matrix([[1,2,3], [4,5,6]])
print('a=', a)
print(19*'-')
print('m=', m)
print(19*'-')
print('shape(a) = ', np.shape(a))
print('a.shape = ', a.shape)
print(19*'-')
print('np.shape(m) = ', np.shape(m))
print('m.shape = ', m.shape)


a= [[1 2 3]
 [4 5 6]
 [7 8 9]]
-------------------
m= [[1 2 3]
 [4 5 6]]
-------------------
shape(a) =  (3, 3)
a.shape =  (3, 3)
-------------------
np.shape(m) =  (2, 3)
m.shape =  (2, 3)

get the number of elements of the n-th dimension of array a. (Note that MATLAB® uses 1 based indexing while Python uses 0 based indexing, See note [INDEXING](https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html#numpy-for-matlab-users-notes)

MATLAB Numpy
size(a,n) a.shape[n-1]

In [5]:
a = np.array([[1,2,3], [4,5,6], [7,8,9]])
m = np.matrix([[1,2,3], [4,5,6]])
print('a=', a)
print(19*'-')
print('m=', m)
print(19*'-')
print('a.shape[2-1] = ', a.shape[2-1])
print(19*'-')
print('m.shape[2-1] = ', m.shape[2-1])


a= [[1 2 3]
 [4 5 6]
 [7 8 9]]
-------------------
m= [[1 2 3]
 [4 5 6]]
-------------------
a.shape[2-1] =  3
-------------------
m.shape[2-1] =  3

2x3 matrix literal

MATLAB Numpy
[ 1 2 3; 4 5 6 ] array([[1.,2.,3.], [4.,5.,6.]])

In [6]:
a = np.array([[1.,2.,3.], [4.,5.,6.]])
m = np.matrix([[1.,2.,3.], [4.,5.,6.]])
print('a=', a)
print(19*'-')
print('m=', m)


a= [[ 1.  2.  3.]
 [ 4.  5.  6.]]
-------------------
m= [[ 1.  2.  3.]
 [ 4.  5.  6.]]

construct a matrix from blocks a, b, c, and d

MATLAB Numpy
[ a b; c d ] vstack([hstack([a,b]), hstack([c,d])]) or bmat('a b; c d').A

In [7]:
a = np.array([[1.,2.,3.], [4.,5.,6.]])
b = np.array([[10.,20.,30.], [40.,50.,60.]])
c = np.array([[11.,12.,13.], [14.,15.,16.]])
d = np.array([[19.,29.,39.], [49.,59.,69.]])


m = np.matrix([[1.,2.,3.], [4.,5.,6.]])
n = np.matrix([[10.,20.,30.], [40.,50.,60.]])
r = np.matrix([[11.,12.,13.], [14.,15.,16.]])
p = np.matrix([[19.,29.,39.], [49.,59.,69.]])

In [8]:
e = np.vstack([np.hstack([a,b]), np.hstack([c,d])])
q = np.vstack([np.hstack([m,n]), np.hstack([r,p])])

print ('e = ', e)
print ('q = ', q)


e =  [[  1.   2.   3.  10.  20.  30.]
 [  4.   5.   6.  40.  50.  60.]
 [ 11.  12.  13.  19.  29.  39.]
 [ 14.  15.  16.  49.  59.  69.]]
q =  [[  1.   2.   3.  10.  20.  30.]
 [  4.   5.   6.  40.  50.  60.]
 [ 11.  12.  13.  19.  29.  39.]
 [ 14.  15.  16.  49.  59.  69.]]

In [9]:
f = np.bmat('a b; c d').A
s = np.bmat('m n; r p').A

print ('f = ', f)
print ('s = ', s)


f =  [[  1.   2.   3.  10.  20.  30.]
 [  4.   5.   6.  40.  50.  60.]
 [ 11.  12.  13.  19.  29.  39.]
 [ 14.  15.  16.  49.  59.  69.]]
s =  [[  1.   2.   3.  10.  20.  30.]
 [  4.   5.   6.  40.  50.  60.]
 [ 11.  12.  13.  19.  29.  39.]
 [ 14.  15.  16.  49.  59.  69.]]

access last element in the 1xn matrix a

MATLAB Numpy
a(end) a[-1]

In [10]:
a = np.array([1,2,3,4])
print(a[-1])


4

access last element in the 1xn matrix a

MATLAB Numpy
a(2,5) a[1,4]

In [11]:
a = np.array([[1.,2.,3.,4.,5.], [6.,7.,8.,9.,10.],[11.,12.,13.,14.,15.]])
m = np.matrix([[1.,2.,3.,4.,5.], [6.,7.,8.,9.,10.],[11.,12.,13.,14.,15.]])

print('a=', a)
print(39*'-')
print('m=', m)
print(39*'-')
print(a[1,4])
print(39*'-')
print(m[1,4])


a= [[  1.   2.   3.   4.   5.]
 [  6.   7.   8.   9.  10.]
 [ 11.  12.  13.  14.  15.]]
---------------------------------------
m= [[  1.   2.   3.   4.   5.]
 [  6.   7.   8.   9.  10.]
 [ 11.  12.  13.  14.  15.]]
---------------------------------------
10.0
---------------------------------------
10.0
entire second row of a
MATLAB Numpy
a(2,:) a[1] or a[1,:]

In [12]:
a = np.array([[1.,2.,3.,4.,5.], [6.,7.,8.,9.,10.],[11.,12.,13.,14.,15.]])
m = np.matrix([[1.,2.,3.,4.,5.], [6.,7.,8.,9.,10.],[11.,12.,13.,14.,15.]])

print('a=', a)
print(39*'-')
print('m=', m)
print(39*'-')
print('2nd row of a: a[1] = ', a[1])
print('2nd row of a: a[1:] = ', a[1,:])
print(39*'-')
print('2nd row of m: m[1] = ', m[1])  
print('2nd row of m: m[1:]', m[1,:])


a= [[  1.   2.   3.   4.   5.]
 [  6.   7.   8.   9.  10.]
 [ 11.  12.  13.  14.  15.]]
---------------------------------------
m= [[  1.   2.   3.   4.   5.]
 [  6.   7.   8.   9.  10.]
 [ 11.  12.  13.  14.  15.]]
---------------------------------------
2nd row of a: a[1] =  [  6.   7.   8.   9.  10.]
2nd row of a: a[1:] =  [  6.   7.   8.   9.  10.]
---------------------------------------
2nd row of m: m[1] =  [[  6.   7.   8.   9.  10.]]
2nd row of m: m[1:] [[  6.   7.   8.   9.  10.]]

the first five rows of a

MATLAB Numpy
a(1:5,:) a[0:5] or a[:5] or a[0:5,:]

In [29]:
a=np.random.rand(8,5)
print(a)


[[ 0.90168486  0.14441001  0.48392975  0.29779663  0.75222576]
 [ 0.27371836  0.83489724  0.61806446  0.09229072  0.45914082]
 [ 0.79728052  0.31535318  0.65536878  0.34827956  0.08814647]
 [ 0.84352843  0.34844242  0.13166015  0.0336106   0.49196678]
 [ 0.66322826  0.99185531  0.79669518  0.93938576  0.74426238]
 [ 0.18148052  0.78393026  0.13856042  0.15049394  0.20812258]
 [ 0.37543898  0.45854521  0.80779713  0.13492152  0.59396338]
 [ 0.72605971  0.73162901  0.624593    0.65987329  0.3144167 ]]

In [14]:
a[0:5]


Out[14]:
array([[ 0.42889877,  0.33620741,  0.47738437,  0.59888239,  0.57585896],
       [ 0.05522298,  0.09217045,  0.39757494,  0.97341008,  0.55355556],
       [ 0.88976809,  0.04376168,  0.47362511,  0.7846153 ,  0.57489216],
       [ 0.55314855,  0.86649296,  0.03492   ,  0.70319555,  0.50767356],
       [ 0.57340474,  0.84232345,  0.58390913,  0.38526577,  0.89967711]])

In [15]:
a[:5]


Out[15]:
array([[ 0.42889877,  0.33620741,  0.47738437,  0.59888239,  0.57585896],
       [ 0.05522298,  0.09217045,  0.39757494,  0.97341008,  0.55355556],
       [ 0.88976809,  0.04376168,  0.47362511,  0.7846153 ,  0.57489216],
       [ 0.55314855,  0.86649296,  0.03492   ,  0.70319555,  0.50767356],
       [ 0.57340474,  0.84232345,  0.58390913,  0.38526577,  0.89967711]])

In [16]:
a[0:5,:]


Out[16]:
array([[ 0.42889877,  0.33620741,  0.47738437,  0.59888239,  0.57585896],
       [ 0.05522298,  0.09217045,  0.39757494,  0.97341008,  0.55355556],
       [ 0.88976809,  0.04376168,  0.47362511,  0.7846153 ,  0.57489216],
       [ 0.55314855,  0.86649296,  0.03492   ,  0.70319555,  0.50767356],
       [ 0.57340474,  0.84232345,  0.58390913,  0.38526577,  0.89967711]])

In [17]:
m = np.mat(a) #or np.asmatrix(a)

In [18]:
m


Out[18]:
matrix([[ 0.42889877,  0.33620741,  0.47738437,  0.59888239,  0.57585896],
        [ 0.05522298,  0.09217045,  0.39757494,  0.97341008,  0.55355556],
        [ 0.88976809,  0.04376168,  0.47362511,  0.7846153 ,  0.57489216],
        [ 0.55314855,  0.86649296,  0.03492   ,  0.70319555,  0.50767356],
        [ 0.57340474,  0.84232345,  0.58390913,  0.38526577,  0.89967711],
        [ 0.00653804,  0.68068708,  0.19925952,  0.35977614,  0.9561028 ],
        [ 0.09963968,  0.78858858,  0.49462647,  0.88929536,  0.91274072],
        [ 0.59365336,  0.38232815,  0.93805704,  0.27750732,  0.44905923]])

In [19]:
m[0:5]


Out[19]:
matrix([[ 0.42889877,  0.33620741,  0.47738437,  0.59888239,  0.57585896],
        [ 0.05522298,  0.09217045,  0.39757494,  0.97341008,  0.55355556],
        [ 0.88976809,  0.04376168,  0.47362511,  0.7846153 ,  0.57489216],
        [ 0.55314855,  0.86649296,  0.03492   ,  0.70319555,  0.50767356],
        [ 0.57340474,  0.84232345,  0.58390913,  0.38526577,  0.89967711]])

In [20]:
m[:5]


Out[20]:
matrix([[ 0.42889877,  0.33620741,  0.47738437,  0.59888239,  0.57585896],
        [ 0.05522298,  0.09217045,  0.39757494,  0.97341008,  0.55355556],
        [ 0.88976809,  0.04376168,  0.47362511,  0.7846153 ,  0.57489216],
        [ 0.55314855,  0.86649296,  0.03492   ,  0.70319555,  0.50767356],
        [ 0.57340474,  0.84232345,  0.58390913,  0.38526577,  0.89967711]])

In [21]:
m[0:5,:]


Out[21]:
matrix([[ 0.42889877,  0.33620741,  0.47738437,  0.59888239,  0.57585896],
        [ 0.05522298,  0.09217045,  0.39757494,  0.97341008,  0.55355556],
        [ 0.88976809,  0.04376168,  0.47362511,  0.7846153 ,  0.57489216],
        [ 0.55314855,  0.86649296,  0.03492   ,  0.70319555,  0.50767356],
        [ 0.57340474,  0.84232345,  0.58390913,  0.38526577,  0.89967711]])

the last five rows of a

MATLAB Numpy
a(end-4:end,:) a[-5:]

In [23]:
a[-5:]


Out[23]:
array([[ 0.35167425,  0.49527549,  0.49673432,  0.42039932,  0.787584  ],
       [ 0.01719551,  0.27119864,  0.57420067,  0.58048633,  0.73362629],
       [ 0.63442791,  0.02092427,  0.45161922,  0.40164021,  0.13517475],
       [ 0.83510998,  0.55772054,  0.46047937,  0.51854881,  0.18769949],
       [ 0.38274974,  0.37951801,  0.70084591,  0.83965991,  0.0314651 ]])

In [24]:
m=np.mat(a)
m


Out[24]:
matrix([[ 0.89877659,  0.83228871,  0.42230966,  0.82757469,  0.03596778],
        [ 0.65005996,  0.39457308,  0.75818238,  0.28579483,  0.43883847],
        [ 0.9539496 ,  0.55809072,  0.68078805,  0.67504999,  0.0622288 ],
        [ 0.74233815,  0.3939643 ,  0.13201609,  0.21711141,  0.72957886],
        [ 0.86423089,  0.73604093,  0.24398047,  0.02642547,  0.04758567],
        [ 0.35167425,  0.49527549,  0.49673432,  0.42039932,  0.787584  ],
        [ 0.01719551,  0.27119864,  0.57420067,  0.58048633,  0.73362629],
        [ 0.63442791,  0.02092427,  0.45161922,  0.40164021,  0.13517475],
        [ 0.83510998,  0.55772054,  0.46047937,  0.51854881,  0.18769949],
        [ 0.38274974,  0.37951801,  0.70084591,  0.83965991,  0.0314651 ]])

In [25]:
m[-5:]


Out[25]:
matrix([[ 0.35167425,  0.49527549,  0.49673432,  0.42039932,  0.787584  ],
        [ 0.01719551,  0.27119864,  0.57420067,  0.58048633,  0.73362629],
        [ 0.63442791,  0.02092427,  0.45161922,  0.40164021,  0.13517475],
        [ 0.83510998,  0.55772054,  0.46047937,  0.51854881,  0.18769949],
        [ 0.38274974,  0.37951801,  0.70084591,  0.83965991,  0.0314651 ]])

rows one to three and columns five to nine of a. This gives read-only access.

MATLAB Numpy
a(1:3,5:9) a[0:3][:,4:9]

In [30]:
a=np.random.rand(5,10)
b= a.copy()
print(a)


[[ 0.80197424  0.74580115  0.72793262  0.86587742  0.78988181  0.92360853
   0.45683472  0.21345295  0.90797641  0.70714221]
 [ 0.43291082  0.50619191  0.72054373  0.69927352  0.28945151  0.01792739
   0.48031691  0.03882118  0.10000571  0.02442249]
 [ 0.7308061   0.70547753  0.98780331  0.05019302  0.2206048   0.82735168
   0.94179393  0.1425208   0.35212893  0.13157853]
 [ 0.34365981  0.86841522  0.8835403   0.76367202  0.57839459  0.70851165
   0.72671642  0.01666793  0.7839512   0.95087712]
 [ 0.60405219  0.52356562  0.04250795  0.33827129  0.21794721  0.4854303
   0.92064264  0.9808843   0.8100669   0.76788517]]

In [6]:
a[0:3][:,4:9]


Out[6]:
array([[ 0.93731847,  0.08286245,  0.77688497,  0.50167879,  0.17513506],
       [ 0.79114445,  0.46778047,  0.66162481,  0.87936643,  0.28619071],
       [ 0.86185913,  0.45021826,  0.27540787,  0.35777285,  0.80099342]])

rows 2,4 and 5 and columns 1 and 3. This allows the matrix to be modified, and doesn’t require a regular slice

MATLAB Numpy
a([2,4,5],[1,3]) a[np.ix_([1,3,4],[0,2])]

In [7]:
a[np.ix_([1,3,4],[0,2])]


Out[7]:
array([[ 0.44486947,  0.62455323],
       [ 0.63868981,  0.38762882],
       [ 0.45547128,  0.35046572]])

every other row of a, starting with the third and going to the twenty-first

MATLAB Numpy
a(3:2:21,:) a[ 2:21:2,:]

In [8]:
a[2:21:2,:]


Out[8]:
array([[ 0.78697771,  0.26373586,  0.05171165,  0.26548848,  0.86185913,
         0.45021826,  0.27540787,  0.35777285,  0.80099342,  0.24069535],
       [ 0.45547128,  0.21664814,  0.35046572,  0.90592024,  0.72025931,
         0.48046836,  0.87702758,  0.49976765,  0.51446223,  0.37809625]])

In [ ]:

every other row of a, starting with the first
MATLAB Numpy
a(1:2:end,:) a[ ::2,:]

In [9]:
a[::2,:]


Out[9]:
array([[ 0.34261188,  0.77787948,  0.39695463,  0.14708612,  0.93731847,
         0.08286245,  0.77688497,  0.50167879,  0.17513506,  0.23897106],
       [ 0.78697771,  0.26373586,  0.05171165,  0.26548848,  0.86185913,
         0.45021826,  0.27540787,  0.35777285,  0.80099342,  0.24069535],
       [ 0.45547128,  0.21664814,  0.35046572,  0.90592024,  0.72025931,
         0.48046836,  0.87702758,  0.49976765,  0.51446223,  0.37809625]])
a with rows in reverse order
MATLAB Numpy
a(end:-1:1,:) or flipud(a) a[ ::-1,:]

In [10]:
a[ ::-1,:]


Out[10]:
array([[ 0.45547128,  0.21664814,  0.35046572,  0.90592024,  0.72025931,
         0.48046836,  0.87702758,  0.49976765,  0.51446223,  0.37809625],
       [ 0.63868981,  0.46704273,  0.38762882,  0.06768026,  0.91171078,
         0.4549373 ,  0.92167502,  0.12115214,  0.65141904,  0.62915646],
       [ 0.78697771,  0.26373586,  0.05171165,  0.26548848,  0.86185913,
         0.45021826,  0.27540787,  0.35777285,  0.80099342,  0.24069535],
       [ 0.44486947,  0.42976226,  0.62455323,  0.28680072,  0.79114445,
         0.46778047,  0.66162481,  0.87936643,  0.28619071,  0.02988731],
       [ 0.34261188,  0.77787948,  0.39695463,  0.14708612,  0.93731847,
         0.08286245,  0.77688497,  0.50167879,  0.17513506,  0.23897106]])
a with copy of the first row appended to the end
MATLAB Numpy
a([1:end 1],:) a[np.r_[:len(a),0]]

In [11]:
a[np.r_[:len(a),0]]


Out[11]:
array([[ 0.34261188,  0.77787948,  0.39695463,  0.14708612,  0.93731847,
         0.08286245,  0.77688497,  0.50167879,  0.17513506,  0.23897106],
       [ 0.44486947,  0.42976226,  0.62455323,  0.28680072,  0.79114445,
         0.46778047,  0.66162481,  0.87936643,  0.28619071,  0.02988731],
       [ 0.78697771,  0.26373586,  0.05171165,  0.26548848,  0.86185913,
         0.45021826,  0.27540787,  0.35777285,  0.80099342,  0.24069535],
       [ 0.63868981,  0.46704273,  0.38762882,  0.06768026,  0.91171078,
         0.4549373 ,  0.92167502,  0.12115214,  0.65141904,  0.62915646],
       [ 0.45547128,  0.21664814,  0.35046572,  0.90592024,  0.72025931,
         0.48046836,  0.87702758,  0.49976765,  0.51446223,  0.37809625],
       [ 0.34261188,  0.77787948,  0.39695463,  0.14708612,  0.93731847,
         0.08286245,  0.77688497,  0.50167879,  0.17513506,  0.23897106]])
transpose of a
MATLAB Numpy
a.' a.transpose() or a.T

In [12]:
a.transpose()


Out[12]:
array([[ 0.34261188,  0.44486947,  0.78697771,  0.63868981,  0.45547128],
       [ 0.77787948,  0.42976226,  0.26373586,  0.46704273,  0.21664814],
       [ 0.39695463,  0.62455323,  0.05171165,  0.38762882,  0.35046572],
       [ 0.14708612,  0.28680072,  0.26548848,  0.06768026,  0.90592024],
       [ 0.93731847,  0.79114445,  0.86185913,  0.91171078,  0.72025931],
       [ 0.08286245,  0.46778047,  0.45021826,  0.4549373 ,  0.48046836],
       [ 0.77688497,  0.66162481,  0.27540787,  0.92167502,  0.87702758],
       [ 0.50167879,  0.87936643,  0.35777285,  0.12115214,  0.49976765],
       [ 0.17513506,  0.28619071,  0.80099342,  0.65141904,  0.51446223],
       [ 0.23897106,  0.02988731,  0.24069535,  0.62915646,  0.37809625]])

In [13]:
a.T


Out[13]:
array([[ 0.34261188,  0.44486947,  0.78697771,  0.63868981,  0.45547128],
       [ 0.77787948,  0.42976226,  0.26373586,  0.46704273,  0.21664814],
       [ 0.39695463,  0.62455323,  0.05171165,  0.38762882,  0.35046572],
       [ 0.14708612,  0.28680072,  0.26548848,  0.06768026,  0.90592024],
       [ 0.93731847,  0.79114445,  0.86185913,  0.91171078,  0.72025931],
       [ 0.08286245,  0.46778047,  0.45021826,  0.4549373 ,  0.48046836],
       [ 0.77688497,  0.66162481,  0.27540787,  0.92167502,  0.87702758],
       [ 0.50167879,  0.87936643,  0.35777285,  0.12115214,  0.49976765],
       [ 0.17513506,  0.28619071,  0.80099342,  0.65141904,  0.51446223],
       [ 0.23897106,  0.02988731,  0.24069535,  0.62915646,  0.37809625]])
aconjugate transpose of a
MATLAB Numpy
a' a.conj().transpose() or a.conj().T

In [14]:
a.conj().T


Out[14]:
array([[ 0.34261188,  0.44486947,  0.78697771,  0.63868981,  0.45547128],
       [ 0.77787948,  0.42976226,  0.26373586,  0.46704273,  0.21664814],
       [ 0.39695463,  0.62455323,  0.05171165,  0.38762882,  0.35046572],
       [ 0.14708612,  0.28680072,  0.26548848,  0.06768026,  0.90592024],
       [ 0.93731847,  0.79114445,  0.86185913,  0.91171078,  0.72025931],
       [ 0.08286245,  0.46778047,  0.45021826,  0.4549373 ,  0.48046836],
       [ 0.77688497,  0.66162481,  0.27540787,  0.92167502,  0.87702758],
       [ 0.50167879,  0.87936643,  0.35777285,  0.12115214,  0.49976765],
       [ 0.17513506,  0.28619071,  0.80099342,  0.65141904,  0.51446223],
       [ 0.23897106,  0.02988731,  0.24069535,  0.62915646,  0.37809625]])

In [15]:
a.conj().transpose()


Out[15]:
array([[ 0.34261188,  0.44486947,  0.78697771,  0.63868981,  0.45547128],
       [ 0.77787948,  0.42976226,  0.26373586,  0.46704273,  0.21664814],
       [ 0.39695463,  0.62455323,  0.05171165,  0.38762882,  0.35046572],
       [ 0.14708612,  0.28680072,  0.26548848,  0.06768026,  0.90592024],
       [ 0.93731847,  0.79114445,  0.86185913,  0.91171078,  0.72025931],
       [ 0.08286245,  0.46778047,  0.45021826,  0.4549373 ,  0.48046836],
       [ 0.77688497,  0.66162481,  0.27540787,  0.92167502,  0.87702758],
       [ 0.50167879,  0.87936643,  0.35777285,  0.12115214,  0.49976765],
       [ 0.17513506,  0.28619071,  0.80099342,  0.65141904,  0.51446223],
       [ 0.23897106,  0.02988731,  0.24069535,  0.62915646,  0.37809625]])
matrix multiply
MATLAB Numpy
a * b a.dot(b)

In [16]:
a.dot(np.asarray(m))


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-16-ce9dbd0c621c> in <module>()
----> 1 a.dot(np.asarray(m))

NameError: name 'm' is not defined
element-wise multiply
MATLAB Numpy
a .* b a * b

In [17]:
a*a


Out[17]:
array([[ 0.1173829 ,  0.60509648,  0.15757298,  0.02163433,  0.87856591,
         0.00686619,  0.60355026,  0.2516816 ,  0.03067229,  0.05710717],
       [ 0.19790885,  0.1846956 ,  0.39006673,  0.08225465,  0.62590954,
         0.21881857,  0.43774739,  0.77328532,  0.08190512,  0.00089325],
       [ 0.61933392,  0.0695566 ,  0.00267409,  0.07048413,  0.74280116,
         0.20269648,  0.07584949,  0.12800141,  0.64159046,  0.05793425],
       [ 0.40792467,  0.21812891,  0.1502561 ,  0.00458062,  0.83121655,
         0.20696794,  0.84948484,  0.01467784,  0.42434677,  0.39583786],
       [ 0.20745408,  0.04693642,  0.12282622,  0.82069148,  0.51877348,
         0.23084984,  0.76917738,  0.2497677 ,  0.26467139,  0.14295677]])
element-wise divide
MATLAB Numpy
a./ b a/b

In [18]:
a/a


Out[18]:
array([[ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]])
element-wise exponentiation
MATLAB Numpy
a.^3 a**3

In [19]:
a**3


Out[19]:
array([[  4.02167758e-02,   4.70692134e-01,   6.25493232e-02,
          3.18210902e-03,   8.23496050e-01,   5.68949013e-04,
          4.68889126e-01,   1.26263322e-01,   5.37179326e-03,
          1.36469598e-02],
       [  8.80436059e-02,   7.93752004e-02,   2.43617438e-01,
          2.35906935e-02,   4.95184859e-01,   1.02359052e-01,
          2.89624535e-01,   6.80001150e-01,   2.34404854e-02,
          2.66968913e-05],
       [  4.87401989e-01,   1.83445708e-02,   1.38281812e-04,
          1.87127253e-02,   6.40189955e-01,   9.12576564e-02,
          2.08895477e-02,   4.57954284e-02,   5.13909741e-01,
          1.39445058e-02],
       [  2.60537332e-01,   1.01875521e-01,   5.82435962e-02,
          3.10017394e-04,   7.57829089e-01,   9.41574362e-02,
          7.82948956e-01,   1.77825180e-03,   2.76427566e-01,
          2.49043947e-01],
       [  9.44893771e-02,   1.01686880e-02,   4.30463810e-02,
          7.43481028e-01,   3.73651428e-01,   1.10916045e-01,
          6.74589782e-01,   1.24825816e-01,   1.36163433e-01,
          5.40514190e-02]])
matrix whose i,jth element is (a_ij > 0.5). The Matlab result is an array of 0s and 1s. The NumPy result is an array of the boolean values False and True.
MATLAB Numpy
(a>0.5) (a>0.5)

In [20]:
a>0.5


Out[20]:
array([[False,  True, False, False,  True, False,  True,  True, False,
        False],
       [False, False,  True, False,  True, False,  True,  True, False,
        False],
       [ True, False, False, False,  True, False, False, False,  True,
        False],
       [ True, False, False, False,  True, False,  True, False,  True,
         True],
       [False, False, False,  True,  True, False,  True, False,  True,
        False]], dtype=bool)
find the indices where (a > 0.5)
MATLAB Numpy
find(a>0.5) nonzero(a>0.5)

In [21]:
np.nonzero(a>0.5)


Out[21]:
(array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4]),
 array([1, 4, 6, 7, 2, 4, 6, 7, 0, 4, 8, 0, 4, 6, 8, 9, 3, 4, 6, 8]))
extract the columms of a where vector v > 0.5
MATLAB Numpy
a(:,find(v>0.5)) a[:,nonzero(v>0.5)[0]]

In [22]:
v = a[:,4].T
a[:,np.nonzero(v>0.5)[0]]


Out[22]:
array([[ 0.34261188,  0.77787948,  0.39695463,  0.14708612,  0.93731847],
       [ 0.44486947,  0.42976226,  0.62455323,  0.28680072,  0.79114445],
       [ 0.78697771,  0.26373586,  0.05171165,  0.26548848,  0.86185913],
       [ 0.63868981,  0.46704273,  0.38762882,  0.06768026,  0.91171078],
       [ 0.45547128,  0.21664814,  0.35046572,  0.90592024,  0.72025931]])
extract the columms of a where column vector v > 0.5
MATLAB Numpy
a(:,find(v>0.5)) a[:,v.T>0.5]

In [23]:
a[:,v.T>0.5]


/home/jimmy/.local/lib/python3.5/site-packages/ipykernel/__main__.py:1: VisibleDeprecationWarning: boolean index did not match indexed array along dimension 1; dimension is 10 but corresponding boolean dimension is 5
  if __name__ == '__main__':
Out[23]:
array([[ 0.34261188,  0.77787948,  0.39695463,  0.14708612,  0.93731847],
       [ 0.44486947,  0.42976226,  0.62455323,  0.28680072,  0.79114445],
       [ 0.78697771,  0.26373586,  0.05171165,  0.26548848,  0.86185913],
       [ 0.63868981,  0.46704273,  0.38762882,  0.06768026,  0.91171078],
       [ 0.45547128,  0.21664814,  0.35046572,  0.90592024,  0.72025931]])
a with elements less than 0.5 zeroed out
MATLAB Numpy
a(a<0.5)=0 a[a<0.5]=0

In [41]:
a = b.copy()

a[a<0.5]=0
print(a)


[[ 0.80197424  0.74580115  0.72793262  0.86587742  0.78988181  0.92360853
   0.          0.          0.90797641  0.70714221]
 [ 0.          0.50619191  0.72054373  0.69927352  0.          0.          0.
   0.          0.          0.        ]
 [ 0.7308061   0.70547753  0.98780331  0.          0.          0.82735168
   0.94179393  0.          0.          0.        ]
 [ 0.          0.86841522  0.8835403   0.76367202  0.57839459  0.70851165
   0.72671642  0.          0.7839512   0.95087712]
 [ 0.60405219  0.52356562  0.          0.          0.          0.
   0.92064264  0.9808843   0.8100669   0.76788517]]
a with elements less than 0.5 zeroed out
MATLAB Numpy
a .* (a>0.5) a * (a>0.5)

In [48]:
a = b.copy()
a * (a>0.5)


Out[48]:
array([[ 0.80197424,  0.74580115,  0.72793262,  0.86587742,  0.78988181,
         0.92360853,  0.        ,  0.        ,  0.90797641,  0.70714221],
       [ 0.        ,  0.50619191,  0.72054373,  0.69927352,  0.        ,
         0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.7308061 ,  0.70547753,  0.98780331,  0.        ,  0.        ,
         0.82735168,  0.94179393,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.86841522,  0.8835403 ,  0.76367202,  0.57839459,
         0.70851165,  0.72671642,  0.        ,  0.7839512 ,  0.95087712],
       [ 0.60405219,  0.52356562,  0.        ,  0.        ,  0.        ,
         0.        ,  0.92064264,  0.9808843 ,  0.8100669 ,  0.76788517]])
set all values to the same scalar value
MATLAB Numpy
a(:) = 3 a[:] = 3

In [52]:
a[:] = 3
a


Out[52]:
array([[ 3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.]])
numpy assigns by reference
MATLAB Numpy
y=x y = x.copy()

In [4]:
a=np.random.rand(2,2)
c = a.copy()
b = a
print(a), print(b)
# changing b now changes a (anf vise veras)
b[1,1] = 0
print(a)
print(b)
a[0,0] = -1
print(a)
print(b)
# changing c does not change a (and vise versa)
a[0,1] = -10
print(a)
print(c)
c[1,0] = 20
print(a)
print(c)


[[ 0.34891224  0.51991569]
 [ 0.14870345  0.46541568]]
[[ 0.34891224  0.51991569]
 [ 0.14870345  0.46541568]]
[[ 0.34891224  0.51991569]
 [ 0.14870345  0.        ]]
[[ 0.34891224  0.51991569]
 [ 0.14870345  0.        ]]
[[-1.          0.51991569]
 [ 0.14870345  0.        ]]
[[-1.          0.51991569]
 [ 0.14870345  0.        ]]
[[ -1.         -10.        ]
 [  0.14870345   0.        ]]
[[ 0.34891224  0.51991569]
 [ 0.14870345  0.46541568]]
[[ -1.         -10.        ]
 [  0.14870345   0.        ]]
[[  0.34891224   0.51991569]
 [ 20.           0.46541568]]
numpy slices are by reference
MATLAB Numpy
y=x(2,:) y = x[1,:].copy()

In [8]:
y=a[1,:]
print(a)
print(y)
a[1,1]=1
print(y)


[[ -1.         -10.        ]
 [  0.14870345   0.        ]]
[ 0.14870345  0.        ]
[ 0.14870345  1.        ]
turn array into vector (note that this forces a copy)
MATLAB Numpy
y=x(:) y = x.flatten()

In [9]:
a.flatten()


Out[9]:
array([ -1.        , -10.        ,   0.14870345,   1.        ])
create an increasing vector (see note [RANGES](https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html#numpy-for-matlab-users-notes))
MATLAB Numpy
1:10 np.arange(1.,11.) or np.r_[1.:11.] or np.r_[1:10:10j]

In [10]:
a = np.arange(1,11)
create an increasing vector (see note [RANGES](https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html#numpy-for-matlab-users-notes))
MATLAB Numpy
0:9 np.arange(10.) or r_[:10.] or r_[:9:10j]

In [11]:
a = np.arange(10)
create a column vector
MATLAB Numpy
[1:10]' np.arange(1.,11.)[:, newaxis]

In [ ]:

3x4 two-dimensional array full of 64-bit floating point zeros
MATLAB Numpy
zeros(3,4) np.zeros((3,4))

In [20]:
a = np.zeros((3,5))
print(a)


[[ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]]
3x4x5 three-dimensional array full of 64-bit floating point zeros
MATLAB Numpy
zeros(3,4,5) np.zeros((3,4,5))

In [19]:
a = np.zeros((2,3,5))
print(a)


[[[ 0.  0.  0.  0.  0.]
  [ 0.  0.  0.  0.  0.]
  [ 0.  0.  0.  0.  0.]]

 [[ 0.  0.  0.  0.  0.]
  [ 0.  0.  0.  0.  0.]
  [ 0.  0.  0.  0.  0.]]]

3x4 two-dimensional array full of 64-bit floating point ones

MATLAB Numpy
ones(3,4) np.ones((3,4))

In [17]:
a = np.ones((3,4))
print(a)


[[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]

3x3 identity matrix

MATLAB Numpy
eye(3) np.eye(3)

In [15]:
a = np.eye(3)
print(a)


[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]

vector of diagonal elements of a

MATLAB Numpy
diag(a) np.diag(a)

In [13]:
a=np.random.rand(4,4)
b = np.diag(a)
print(a)
print(b)


[[ 0.62920503  0.51913634  0.89190596  0.31272833]
 [ 0.87033037  0.61714576  0.17373551  0.43472922]
 [ 0.59806779  0.10151691  0.50137355  0.80434858]
 [ 0.5426589   0.79382194  0.41214454  0.44633579]]
[ 0.62920503  0.61714576  0.50137355  0.44633579]

square diagonal matrix whose nonzero values are the elements of a

MATLAB Numpy
diag(a,0) np.diag(a,0)

In [ ]:

random 3x4 matrix

MATLAB Numpy
rand(3,4) np.random.rand(3,4))

In [ ]:

4 equally spaced samples between 1 and 3, inclusive

MATLAB Numpy
linspace(1,3,4) np.linspace(1,3,4)

In [ ]:

two 2D arrays: one of x values, the other of y values

MATLAB Numpy
[x,y]=meshgrid(0:8,0:5) np.mgrid[0:9.,0:6.] or np.meshgrid(r_[0:9.],r_[0:6.]

In [ ]:

the best way to eval functions on a grid

MATLAB Numpy
np.ogrid[0:9.,0:6.] or np.ix_(r_[0:9.],r_[0:6.]

In [ ]:

the best way to eval functions on a grid

MATLAB Numpy
[x,y]=meshgrid([1,2,4],[2,4,5]) np.meshgrid([1,2,4],[2,4,5]) or ix_([1,2,4],[2,4,5])

In [ ]:

create m by n copies of a

MATLAB Numpy
repmat(a, m, n) np.tile(a, (m, n))

concatenate columns of a and b

MATLAB Numpy
[a b] np.concatenate((a,b),1) or np.hstack((a,b)) or np.column_stack((a,b)) or np.c_[a,b]

concatenate rows of a and b

MATLAB Numpy
[a; b] np.concatenate((a,b)) or np.vstack((a,b)) or np.r_[a,b]

maximum element of a (with ndims(a)<=2 for matlab)

MATLAB Numpy
max(max(a)) a.max()

maximum element of each column of matrix a

MATLAB Numpy
max(a) a.max(0)

maximum element of each row of matrix a

MATLAB Numpy
max(a,[ ],2) a.max(1)

compares a and b element-wise, and returns the maximum value from each pair

MATLAB Numpy
max(a,b) maximum(a, b)

L2 norm of vector v

MATLAB Numpy
norm(v) sqrt(dot(v,v)) or np.linalg.norm(v)

element-by-element AND operator (NumPy ufunc) See note LOGICOPS

MATLAB Numpy
a & b logical_and(a,b)

element-by-element OR operator (NumPy ufunc) See note LOGICOPS

MATLAB Numpy
a | b logical_or(a,b)

bitwise AND operator (Python native and NumPy ufunc)

MATLAB Numpy
bitand(a,b) a & b

bitwise OR operator (Python native and NumPy ufunc)

MATLAB Numpy
bitor(a,b) a | b

inverse of square matrix a

MATLAB Numpy
inv(a) linalg.inv(a)

pseudo-inverse of matrix a

MATLAB Numpy
pinv(a) linalg.pinv(a)

matrix rank of a 2D array / matrix a

MATLAB Numpy
rank(a) linalg.matrix_rank(a)

if a is square; linalg.lstsq(a,b) otherwise solution of a x = b for x

MATLAB Numpy
a\b linalg.solve(a,b)

Solve a.T x.T = b.T instead solution of x a = b for x

MATLAB Numpy
b/a )

V = Vh.T singular value decomposition of a

MATLAB Numpy
[U,S,V]=svd(a) U, S, Vh = linalg.svd(a)

cholesky factorization of a matrix (chol(a) in matlab returns an upper triangular matrix, but linalg.cholesky(a) returns a lower triangular matrix)

MATLAB Numpy
chol(a) linalg.cholesky(a).T

eigenvalues and eigenvectors of a

MATLAB Numpy
[V,D]=eig(a) D,V = linalg.eig(a)

eigenvalues and eigenvectors of a, b

MATLAB Numpy
[V,D]=eig(a,b) V,D = np.linalg.eig(a,b)

find the k largest eigenvalues and eigenvectors of a

MATLAB Numpy
[V,D]=eigs(a,k)

QR decomposition

MATLAB Numpy
[Q,R,P]=qr(a,0) Q,R = scipy.linalg.qr(a)

LU decomposition (note: P(Matlab) == transpose(P(numpy)) )

MATLAB Numpy
[L,U,P]=lu(a) L,U = scipy.linalg.lu(a) or LU,P=scipy.linalg.lu_factor(a)

Conjugate gradients solver

MATLAB Numpy
conjgrad scipy.sparse.linalg.cg

Fourier transform of a

MATLAB Numpy
fft(a) fft(a)

inverse Fourier transform of a

MATLAB Numpy
ifft(a) ifft(a)

sort the matrix

MATLAB Numpy
ort(a) sort(a) or a.sort()

sort the rows of the matrix

MATLAB Numpy
[b,I] = sortrows(a,i) I = argsort(a[:,i]), b=a[I,:]

multilinear regression

MATLAB Numpy
regress(y,X) linalg.lstsq(X,y)

downsample with low-pass filtering

MATLAB Numpy
decimate(x, q) scipy.signal.resample(x, len(x)/q)

MATLAB Numpy
unique(a) unique(a)

MATLAB Numpy
squeeze(a) a.squeeze()

Notes

Submatrix: Assignment to a submatrix can be done with lists of indexes using the ix_ command. E.g., for 2d array a, one might do: ind=[1,3]; a[np.ix_(ind,ind)]+=100.

HELP: There is no direct equivalent of MATLAB’s which command, but the commands help and source will usually list the filename where the function is located. Python also has an inspect module (do import inspect) which provides a getfile that often works.

INDEXING: MATLAB® uses one based indexing, so the initial element of a sequence has index 1. Python uses zero based indexing, so the initial element of a sequence has index 0. Confusion and flamewars arise because each has advantages and disadvantages. One based indexing is consistent with common human language usage, where the “first” element of a sequence has index 1. Zero based indexing simplifies indexing. See also a text by prof.dr. Edsger W. Dijkstra.

RANGES: In MATLAB®, 0:5 can be used as both a range literal and a ‘slice’ index (inside parentheses); however, in Python, constructs like 0:5 can only be used as a slice index (inside square brackets). Thus the somewhat quirky r object was created to allow numpy to have a similarly terse range construction mechanism. Note that r is not called like a function or a constructor, but rather indexed using square brackets, which allows the use of Python’s slice syntax in the arguments.

LOGICOPS: & or | in NumPy is bitwise AND/OR, while in Matlab & and | are logical AND/OR. The difference should be clear to anyone with significant programming experience. The two can appear to work the same, but there are important differences. If you would have used Matlab’s & or | operators, you should use the NumPy ufuncs logical_and/logical_or. The notable differences between Matlab’s and NumPy’s & and | operators are:

Non-logical {0,1} inputs: NumPy’s output is the bitwise AND of the inputs. Matlab treats any non-zero value as 1 and returns the logical AND. For example (3 & 4) in NumPy is 0, while in Matlab both 3 and 4 are considered logical true and (3 & 4) returns 1. Precedence: NumPy’s & operator is higher precedence than logical operators like < and >; Matlab’s is the reverse.

If you know you have boolean arguments, you can get away with using NumPy’s bitwise operators, but be careful with parentheses, like this: z = (x > 1) & (x < 2). The absence of NumPy operator forms of logical_and and logical_or is an unfortunate consequence of Python’s design.

RESHAPE and LINEAR INDEXING: Matlab always allows multi-dimensional arrays to be accessed using scalar or linear indices, NumPy does not. Linear indices are common in Matlab programs, e.g. find() on a matrix returns them, whereas NumPy’s find behaves differently. When converting Matlab code it might be necessary to first reshape a matrix to a linear sequence, perform some indexing operations and then reshape back. As reshape (usually) produces views onto the same storage, it should be possible to do this fairly efficiently. Note that the scan order used by reshape in NumPy defaults to the ‘C’ order, whereas Matlab uses the Fortran order. If you are simply converting to a linear sequence and back this doesn’t matter. But if you are converting reshapes from Matlab code which relies on the scan order, then this Matlab code: z = reshape(x,3,4); should become z = x.reshape(3,4,order=’F’).copy() in NumPy.

Customizing Your Environment

In MATLAB® the main tool available to you for customizing the environment is to modify the search path with the locations of your favorite functions. You can put such customizations into a startup script that MATLAB will run on startup.

NumPy, or rather Python, has similar facilities.

To modify your Python search path to include the locations of your own modules, define the PYTHONPATH environment variable. To have a particular script file executed when the interactive Python interpreter is started, define the PYTHONSTARTUP environment variable to contain the name of your startup script.

Unlike MATLAB®, where anything on your path can be called immediately, with Python you need to first do an ‘import’ statement to make functions in a particular file accessible.

For example you might make a startup script that looks like this (Note: this is just an example, not a statement of “best practices”):

# Make all numpy available via shorter 'num' prefix
import numpy as num

# Make all matlib functions accessible at the top level via M.func()
import numpy.matlib as M

# Make some matlib functions accessible directly at the top level via, e.g. rand(3,3)
from numpy.matlib import rand,zeros,ones,empty,eye

# Define a Hermitian function
def hermitian(A, **kwargs):
    return num.transpose(A,**kwargs).conj()

# Make some shorcuts for transpose,hermitian:

# num.transpose(A) --> T(A)

# hermitian(A) --> H(A)
T = num.transpose
H = hermitian

Links

See http://mathesaurus.sf.net/ for another MATLAB®/NumPy cross-reference.

An extensive list of tools for scientific work with python can be found in the topical software page.

MATLAB® and SimuLink® are registered trademarks of The MathWorks. Table Of Contents

NumPy for Matlab users
    Introduction
    Some Key Differences
    ‘array’ or ‘matrix’? Which should I use?
        Short answer
        Long answer
    Facilities for Matrix Users
    Table of Rough MATLAB-NumPy Equivalents
        General Purpose Equivalents
        Linear Algebra Equivalents
    Notes
    Customizing Your Environment
    Links

Previous topic

Miscellaneous Next topic

Building from source


In [ ]: