Matlab to python a migration guide
Recently, I migrated my MATLAB library for my research, namely doa-tools, to Python because I will no longer have access to MATLAB after graduation. MATLAB is a great tool for array processing related research. However, it is not freely accessible to everyone. Python, on the other hand, is more broadly accessible. Show
The overall migration process was not easy, but was quite smooth. I had to rewrite thousands lines of code to replace MATLAB functions with their NumPy, SciPy, and Matplotlib counterparts. The original MATLAB code was written without classes in mind. With Python classes, I can better organize my code. I also added tests and set up Sphinx to generate documentations. You can check the fully documented Python version here. This article summarizes a list of note I took during the migration process. For a complete manual on moving from MATLAB to Python, always start with NumPy's official migration guide here. The code samples in this articles are based on MATLAB 2017b and Python 3.6. In all Python
code samples, we will assume that Multidimensional arraysIn MATLAB, every variable is a multidimensional array[1]. This is definitely not the case for Python. In Python, we use NumPy to manipulate multidimensional arrays. Although the MATLAB syntax and NumPy syntax share a lot of similarities, there are still many notable differences. Row-major order is used by defaultNumPy stores elements in row-major order by default, while MATLAB stores elements in column-major order. Therefore, in NumPy, MATLAB (column-major order): Matrix layout: [A11A12 A13A21A22A23 A31A32A33]⟹ Memory layout: [A11A21A31 A12A22A32A 13A23A33]\text{Matrix layout: } \begin{bmatrix} A_{11} & A_{12} & A_{13}\\ A_{21} & A_{22} & A_{23}\\ A_{31} & A_{32} & A_{33} \end{bmatrix} \implies \text{Memory layout: } \begin{bmatrix} A_{11} & A_{21} & A_{31} & A_{12} & A_{22} & A_{32} & A_{13} & A_{23} & A_{33} \end{bmatrix} NumPy (row-major order): Matrix layout: [A11A12A13A21 A22A23A31 A32A33]⟹Memory layout: [A 11A12A13A21A22A23A31A32 A33]\text{Matrix layout: } \begin{bmatrix} A_{11} & A_{12} & A_{13}\\ A_{21} & A_{22} & A_{23}\\ A_{31} & A_{32} & A_{33} \end{bmatrix} \implies \text{Memory layout: } \begin{bmatrix} A_{11} & A_{12} & A_{13} & A_{21} & A_{22} & A_{23} & A_{31} & A_{32} & A_{33} \end{bmatrix} I first encountered this issue when implementing the vec(⋅)\mathrm{vec}(\cdot) operation, which
converts a matrix to a column vector by stack all its columns together. In MATLAB, this operation can be simply implemented using MATLAB:
Python:
There is no linear indexingIn MATLAB, one can access a single element in a multidimensional array with a single index. This
indexing scheme is called linear indexing[2]. For instance, if A\mathbf{A} is a 3×33\times3 matrix, MATLAB:
Python:
There exist 1D arrays and 0D arraysMATLAB is designed to manipulate matrices, and every matrix variable is at least 2D ( MATLAB:
Python:
Singleton dimensions can be automatically removedIn MATLAB, when extracting a row, a column, or a slice from a multidimensional array, singleton dimensions are not automatically removed and sometimes you need to use
In NumPy, singleton dimensions can be automatically removed, saving you from extra calls to MATLAB:
Python:
You need to explicitly copy an array if you need toIn MATLAB, variables are passed by values. You can simply copy a multidimensional array with the assignment operator, In Python, everything is an object and objects are passed by reference. Therefore, multiple variables can refer to the same object. If this object is mutable, changes will be visible to all the variables referencing it. You need to explicitly make a copy if you need to. In NumPy, basic slicing and transpose creates a view instead of copy, which shares the underlying data storage with the
original array[4]. If you need a copy, you need to explicitly invoke the MATLAB:
Python:
You will need np.ix_ when extract submatricesSuppose we have two vectors, MATLAB:
Python:
You can get MATLAB-like concatenation with np.blockIn MATLAB,
you can easily concatenate many smaller matrices into a bigger one with MATLAB:
Python:
Linear algebraIn MATLAB, the linear algebra routines are globally available. In Python, these routines can by found under You cannot use apostrophe to obtain the conjugate transposeIn MATLAB, the conjugate transpose (or Hermitian) of a matrix, MATLAB:
Python:
You can use eigh instead of eig for Hermitian matricesIn MATLAB, the In NumPy, there is no such problem because MATLAB:
Python:
Use np.linalg.lstsq to implement mldivide and mrdivideMATLAB overloads MATLAB:
Python:
Signal processingMATLAB provides a rich set of functions for signal processing related applications (e.g., spectral analysis, filtering, filter design etc.). In Python, relevant functions can be found under
SciPy has find_peaks, but does not have imregionalmaxWhen implementing spectrum-based direction-of-arrival estimators, one needs to find the top peaks in the resulting spectrum. In MATLAB, MATLAB:
Python:
OptimizationOptimization problems exist in various engineering applications. doa-tools implemented both the maximum-likelihood based estimators and sparsity-based estimators. The former require a solver that is capable of solving constrained non-convex problems, while the latter require a solver that can efficiently solve l1l_1-regularized least squares problems. MATLAB has built-in functions to solve various optimization problems, while in Python, various solvers are available from third-party libraries. Use scipy.optimize.minimize for general constrained non-convex problemsIn MATLAB, sub-optimal solutions to constrained non-convex problems can be obtained with MATLAB:
Python:
The Python version of CVX is CVXPYCVX is a modeling framework for convex programming problems designed for MATLAB. The Python version is available and is named CVXPY. CVXPY's syntax is very similar to that of the CVX. One advantage of CVXPY is that it support defining parameters, allowing the creation of reusable optimization problems.
MATLAB:
Python:
PlottingMATLAB provides a rich set of plotting options. In Python, similar functionalities are provided by Matplotlib. In the code examples, we assume that
hold on is no longer neededIn MATLAB, MATLAB:
Python:
Remember to call plt.tight_layout() when using subplotsSubplots are supports by Matplotlib. Before calling Stem plots come with baselines by defaultIn MATLAB, stem plots do not come with baselines. However, Matplotlib's stem plots will have
baselines drawn be default. You can remove the baselines by setting MATLAB:
Python:
You need to manually create 3D axes in matplotlibBy default, Matplotlib's axes are for 2D plots. To enable 3D plots, you need to import MATLAB:
Python:
3D plotting can be very slow in MatplotlibRendering 3D plots in MATLAB on modern PCs is very fast because MATLAB plots' rendering are hardware accelerated. Matplotlib currently does not support hardware acceleration, and large 3D plots will take a long time to render. To display complex 3D plots, consider using Mayavi instead of Matplotlib[10]. set_aspect('equal') is broken in 3D plotsIn some cases, you want the three axis in a 3D plot share same scale (e.g., visualizing points on a unit sphere). If you use
Is there a way to convert MATLAB to Python?To convert Matlab to python, a tool named SMOP (Small Matlab and Octave to Python Compiler) is used. This tool is capable of understanding basic Matlab code and then parsing it to python. Although there are always limitations to every tool, this tool works best for small-level codes.
Is Python a good alternative to MATLAB?For all of these reasons, and many more, Python is an excellent choice to replace MATLAB as your programming language of choice. Now that you're convinced to try out Python, read on to find out how to get it on your computer and how to switch from MATLAB! Note: GNU Octave is a free and open-source clone of MATLAB.
Is Python easier than MATLAB?MATLAB has very strong mathematical calculation ability, Python is difficult to do. Python has no matrix support, but the NumPy library can be achieved. MATLAB is particularly good at signal processing, image processing, in which Python is not strong, and performance is also much worse.
Can I use MATLAB code in Python?MATLAB® provides a flexible, two-way integration with many programming languages, including Python. This allows different teams to work together and use MATLAB algorithms within production software and IT systems.
|