In this article I explain how to convert Matlab code to Python using three Python libraries and one tool. The Python libraries are Scipy, Numpy, and Matplotlib; the tool is Jupyter Notebooks.

The use case is anyone who is used to doing research with Matlab and wants to switch to using only free and open source software like Python. We will leave the discussion of why one would want to make the conversion for a separate article.

This article walks you through what you have to learn in order to convert Matlab code and start doing science with Python.

**The Tool: Jupyter Notebooks**

Jupyter Notebooks is a web-based interactive computational environment. That is, it’s a program that runs on your browser and allows you to write and execute Python code. It can simulate the experience of the Matlab Command Line:

Once you run code in one box, global variables, function definitions, import statements, etc., are available throughout the notebook. It’s very useful for quickly querying for the shape of a matrix, or doing a calculation or a function. It also allows you to have plots and graphs appear alongside your code and results.

Visit the Jupyter site for instructions on how to get started using Jupyter notebooks.

You might have an entire suite of Matlab code, with separate function definitions in included .m files. In that case, convert those directly to Python and only use Jupyter for your main program. That is where you will be doing the actual analysis and graphing of data.

So now that you have this tool for writing and working with your new code, let’s get down to the actual conversion.

**Comparing Matlab to Python**

Matlab is, amongst other things, a programming language. It is written with a C-like structure. Converting certain trivial pieces of Matlab code to Python can be as simple as ditching semicolons and using square brackets “[]” in space of parentheses “()”.

A couple things to watch out for:

- Python is zero-indexed whereas Matlab is one-indexed.

Matlab | Python | |
---|---|---|

Array[0] | ––> | Array(1) |

- Certain operators will behave differently in Python than in Matlab which means your code may run normally without errors, but give you different results. A good example is “^” which is the power operator on Matlab; but it’s a bitwise operator in Python.

Matlab | Python | |
---|---|---|

x^y; | ––> | x**y OR np.power(x,y) |

- Matlab uses static typing, whereas python uses Duck typing, Python makes a best guess at what type a variable should have. Sometimes it will be necessary to hard type a variable.

Matlab | Python | |
---|---|---|

float lnfh = 0; | ––> | lnfh = np.float64(0) |

**Python Libraries**

With the main tool – Jupyter – and the basics covered, let’s dive into the three essential libraries: Numpy, Scipy, and Matplotlib.

**Numpy**

Numpy is a Library that adds multi-dimensional array and matrix processing, as well as a large collection of high-level math functions. There are a lot of operations Matlab can do natively that Python can do with Numpy. They are things like exponentials, logarithms, standard deviations, etc.

It is customary to import Numpy as np, and calling Numpy functions using `np.functionName()`

Often Converting a Matlab function to Python is as simple as appending “np.” to the beginning of it

For example:

Matlab | Python | |
---|---|---|

p = 1 – exp( Z(n) * t ); | ––> | p = 1 – np.exp( Z[n] * t ) |

lnN = log( No(n) ) – f * t / V; | ––> | lnN = np.log( No[n] ) – f * t / V |

**Scipy**

Scipy is a Python library used for scientific computing and technical computing. It has functions for signal analysis, statistical computing, Linear Algebra, etc. If a Matlab function is not in Numpy, chances are it will be on Scipy.

It is customary to import Scipy as sp, and calling Scipy functions using `sp.functionName()`

or `sp.module.functionName()`

For example:

Matlab | Python | |
---|---|---|

minimum = fminsearch(f,1) | ––> | minimum = sp. optimize.fmin(f, 1) |

**Matplotlib**

Matplotlib is a python library for 2D plotting. It’s very flexible and customizable, allowing you to produce professional looking graphics, much like you can in Matlab.

It is customary to import Matplotlib as plt, and calling Matplotlib functions using `plt.functionName()`

In Matlab, the command `held` is used to continue adding plots to one figure. In Python once you open a figure all plots will go on that figure until a new figure is declared.

Matplotlib also supports subplots; i.e., multiple plots in one figure. They can be arranged in a grid to the user’s preference. For example:

**THAT’s How you Convert Matlab Code to Python!**

And there you have it. Those are the steps to convert Matlab code to Python. This is by far not a comprehensive guide, but if you’re just getting started, this one tool – Jupyter, and three libraries – Numpy, Scipy, and MatplotLib, will be enough to jumpstart your development.

It pays to know these tools as Python becomes a bigger and bigger stake-holder in the research space in Data Science and beyond. For more, check out these articles on Sweetcode:

PyCharm Scientific Mode by Stephan Ofosuhene

Top 10 Python Packages by Dante Sblendorio