Coming from Matlab
Contents
Coming from Matlab#
This chapter is indebted to the excellent numpy documentation.
Matlab is very much built around matrix operations. The biggest difference between Python and Matlab is that Python is designed to do many things that are not matrix manipulation. What this means in practice is that sometimes the notation to do this or that operation in Python (or any other general purpose programming language) is less concise than in Matlab. There is greater competition for each command in Python because it does many more things. However, Python has really first class support for matrices (and tensors, if that’s your thing). In this chapter, we’ll look at some of the common matrix manipulation commands you might use in Matlab and Python.
In MATLAB, the basic data type, even for scalars, is a multidimensional array. Array assignments in MATLAB are stored as 2D arrays of double precision floating point numbers, unless you specify the number of dimensions and type. Operations on the 2D instances of these arrays are modeled on matrix operations in linear algebra. When doing matrix manipulation in Python (using numpy arrays), the basic type will be a multidimensional array. In Python, multiplying 2D arrays with *
is not matrix multiplication–it’s elementbyelement multiplication. (In Python 3.5+, the @
operator can be used for conventional matrix multiplication.)
MATLAB numbers indices from 1; with a(1)
the first element. Like C++, Python is numbered from zero, with, eg, a[0]
as the first element.
Another big difference is that Python and its matrix packages are free and open source.
Matlab <==> Python#
What follows is a giant table of translations between Matlab code and Python’s numpy and scipy packages, which provide a good core set of matrix manipulations. In what follows, we’ll assume that you’ve imported these two packages using
from numpy import *
import scipy.linalg
before using any of the Python commands. In case you’re wondering, from package import *
imports everything from that package so that, instead of calling np.size(a)
you can just call size(a)
.
In what follows, a
and b
will be arrays. For more, see hyperpolyglot.
Matlab 
Python (using numpy and scipy) 





`a 

























































































Although not featured in the table, scipy also has a good range of optimisation algorithms, for instance
from scipy.optimize import minimize
result = minimize(function, start_value, method='NelderMead', tol=1e6)