NumPy for MATLAB users — NumPy v2.3 Manual (original) (raw)

Introduction#

MATLAB® and NumPy have a lot in common, but NumPy was created to work with Python, not to be a MATLAB clone. This guide will help MATLAB users get started with NumPy.

Some key differences#

Rough equivalents#

The table below gives rough equivalents for some common MATLAB expressions. These are similar expressions, not equivalents. For details, see the documentation.

In the table below, it is assumed that you have executed the following commands in Python:

import numpy as np from scipy import io, integrate, linalg, signal from scipy.sparse.linalg import cg, eigs

Also assume below that if the Notes talk about “matrix” that the arguments are two-dimensional entities.

General purpose equivalents#

Linear algebra equivalents#

Notes#

Submatrix: Assignment to a submatrix can be done with lists of indices 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 will usually list the filename where the function is located. Python also has an inspect module (doimport 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 thatr_ 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 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 ufuncslogical_and/logical_or. The notable differences between MATLAB’s and NumPy’s & and | operators are:

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_andand 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.

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

Historically, NumPy has provided a special matrix type, np.matrix, which is a subclass of ndarray which makes binary operations linear algebra operations. You may see it used in some existing code instead of np.array. So, which one to use?

Short answer#

Use arrays.

Until Python 3.5 the only disadvantage of using the array type was that you had to use dot instead of * to multiply (reduce) two tensors (scalar product, matrix vector multiplication etc.). Since Python 3.5 you can use the matrix multiplication @ operator.

Given the above, we intend to deprecate matrix eventually.

Long answer#

NumPy contains both an array class and a matrix class. Thearray 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.

There are pros and cons to using both:

The array is thus much more advisable to use. Indeed, we intend to deprecate matrix eventually.

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.

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 'np' prefix

import numpy as np #

Make the SciPy linear algebra functions available as linalg.func()

e.g. linalg.lu, linalg.eig (for general l*B@u==A@u solution)

from scipy import linalg #

Define a Hermitian function

def hermitian(A, **kwargs): return np.conj(A,**kwargs).T

Make a shortcut for hermitian:

hermitian(A) --> H(A)

H = hermitian

To use the deprecated matrix and other matlib functions:

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 matrix,rand,zeros,ones,empty,eye

Another somewhat outdated MATLAB/NumPy cross-reference can be found athttps://mathesaurus.sf.net/

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

SeeList of Python software: scriptingfor a list of software that use Python as a scripting language

MATLAB® and SimuLink® are registered trademarks of The MathWorks, Inc.