Matlab is used by many students for their thesis projects and many other tasks. Especially in the field of computing and mathematics, Matlab is considered to be a prominent programming language among all. Moreover, as it supports Object-Oriented Programming and Data Visualization codes, you can easily use it to your advantage. But as the world changes, new programming languages come into the picture. To convert Matlab to python, we have two options, either do it manually or take the help of some tool.
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.
In this post, we’ll go through all the available ways to convert Matlab code into python code without any difficulty.
What is Difference Between Matlab and Python Code?
Python is one of the easiest high-level programming languages ever created which is as easy as reading and writing English. It was first released in the 1990s by Guido van Rossum and now is been contributed by hundreds of developers worldwide.
Whereas, Matlab is closed source software managed by Mathworks. And most importantly, Python is free, unlike Matlab.
We can get thousands of modules within Python that can be helped to access any kind of API you need in your project. Moreover, you can edit the original source code of modules in Python.
Whereas, in Matlab, this is next to impossible. Also, the support for python by developers all around the world is increasing at an exponential rate.
According to StatisticsTimes, python is the most searched language in the PYPL index1. Also, considering the usage efficiency and support available, it’s already concluded that Python is way more flexible than Matlab.
Why Conversion to Python is Helps Us?
One main reason to convert Matlab to python is the code simplicity. Python codes are easy to understand which can easily be interpreted even by a new person. Being open-source, it’s always easy to tweak around existing modules and create the best helping module for you. In Matlab, it might not be possible.
Even the original Google algorithm2 was written in Python in the initial stages :D. Isn’t it easier to use open source?
Ways to Convert Matlab To Python
There are many ways to convert Matlab to python. But as python receives more updates, it may or may not be compatible with your current version of Python. It totally depends on the code you’re trying to convert.
1. SMOP (Small Matlab and Octave to Python compiler)
As discussed earlier, SMOP is currently the best available tool to parse and convert Matlab to Python. SMOP also mentions in their documentation that it even surpasses Octave in interpreting the Matlab codes!
Installing SMOP –
git clone https://github.com/victorlei/smop
python setup.py install --user
You need python installed on your computer before running this command. It’ll use the python package installer to install SMOP. If you’re on Linux and do not want to go through this hassle, use this command –
easy_install smop --user
This command will convert the file.m Matlab file and then save it to a.py file. If you want to change the output file, use the -o flag in the terminal. Also, it supports the -d flag which can be used to ignore functions by regex from the file.
matlab2python is a GitHub project created by ebranlard and has a recent commit before 11 months. This project heavily depends on SMOP but has simpler usage capabilities than it. In SMOP, the translation is dependent on libsmop but matlab2python uses numpy to translate array-related declarations.
Installing matlab2python –
git clone https://github.com/ebranlard/matlab2python
pip install -r requirements.txt
Using matlab2python to convert Matlab to python –
python matlab2python.py file.m -o file.py
3. OMPC (Open-Source Matlab-To-Python Compiler)
OMPC works easily and effectively with medium-level Matlab codes. It can easily translate and convert Matlab to python by using a python interpreter. There are two ways to use the OMPC, either by using an online converter or by OMPC locally. We’ll have a look at both these methods –
Online Translator –
Update: Online translator has been shut down by the developers due to some server issues. I’ll update the post, as soon as it’s live again.
Using OMPC locally –
First, you need to clone the zip or tar.gz file and then extract it. Use the following command for this –
tar xvfj tip.bz2
Then in the same directory open the python shell and you can import ompc directly.
Mat2py is an 8 old Github project which uses python to parse Matlab code. It has a proper structure of lexer, parser, and tokens in the source files but as it has not been updated for the past 8 years, we won’t recommend it using over SMOP.
python mat2py.py file.m file.py
Here file.m will be your Matlab file and file.py will be your translated python file.
We suggest you only convert basic Matlab code using this method.
Libermate is another 8-year-old GitHub repo that parses the Matlab code manually and then translates it to python.
Note: The project has been declared as Deprecated and the developer has already suggested using SMOP instead.
You can find the Matlab lexer in the repository which can help you to create your own Matlab lexer. But remember that it’ll still be inferior to SMOP.
Installing Dependencies –
First, save the tar.gz file for pyclibs from here. Then run the following commands –
tar -zxvf pyclips-184.108.40.2068.tar.gz
sudo python setup.py build
sudo python setup.py install
git clone https://github.com/awesomebytes/libermate
python libermate.py file.m
The above command will parse the file.m Matlab file and then create the file.ast with contains the abstract syntax tree of the file and save the translated file to file.py.
Some Other Ways to Create Interface Between Matlab and Python
Apart from translating there are many ways to create an interface between Matlab and python. Thanks to the wonderful community we have a large number of open source projects on this.
pymatlab is a module available in PyPi which can be used to communicate with Matlab code. This module is capable of running functions on certain data and retrieves the results from the function. To install the module, run
pip install pymatlab (pip3 for python3) in your terminal.
session = pymatlab.session_factory()
from numpy.random import randn
a = randn(20,10,30)
b = session.getvalue('B')
The above code initializes a Matlab session and then multiples the array by 3 in Matlab way. Then we can use the getvalue() function to get the value of any variable.
Unlike pymatlab, python-matlab-wormholes is capable of communicating both sides (python to Matlab and Matlab to python). To install –
Fetch the repository from code.google.com repository and extract the tar.gz file. Then run the
python setup.py install command to install the module.
To use Matlab in python –
from Wormhole import Wormhole
W = Wormhole()
import numpy as np
W.execute("y = x.^2")
W.get("y") array([ 0., 1., 4., 9., 16.])
To use python in Matlab –
W = Wormhole
W.execute("y = x**2")
Convert python Ndarray to Matlab Matrix
When using numpy interfaces while interacting with python from Matlab, you can run into an ndarray conversion error. While returning an NxN array from the python function, you’ll notice that it is returned as 1xN many times. This error can be frustrating but fortunately, there has been some good discussion among the community regarding this.
The workaround goes as follows –
data = double(py.array.array('d',py.numpy.nditer(x)));
This will ensure that your data variable is initialized as a matrix of double again.
Convert matlab code system identification toolbox example to python
Matlab has a great tool called System Identification Toolbox which helps you in linear and nonlinear dynamic systems. The examples of this toolbox in Matlab cannot be easily converted to python code as there is no official compatible module in Python to help this.
Fortunately, a researcher named Wilson Rocha Lacerda Junior along with his fellow researchers, published a research paper on “SysIdentPy: A Python package for System Identification using NARMAX models”. SysIdentPy is an open-source package in Python which has similar functionalities to System Identification Toolbox.
pip install sysidentpy to install the package in Python.
How to convert latitude and longitude to local tangent plane python matlab
Geodetic is a widely used module in Matlab to work with angles, coordinates, geometry, and other geology operations. Many softwares require working with latitude and longitude. So, while converting such software Matlab code to python, you’ll run into major problems because there are different packages to handle geology in python.
Among all the options, pymap3d is the best and optimum alternative for the geodetic of Matlab. Use
pip install pymap3d to install the module and start using it right away.
The following example demonstrates how you can use latitude, longitude, and altitude to get local EU coordinates in Python –
import pymap3d as pm
origin = (41.1, 6.5, 1200) #height/altitude is in meters
interest = (41.789, 6.56, 1350)
eu = pm.geodetic2enu(*origin, *interest)
(-5041.419755741586, -76532.89694703609, -612.1412960035814)
Yes, you can convert basic Matlab codes to python by using tools like SMOP, matlab2python, and OMPC. For high-level Matlab codes with multiple modules, you have to manually rewrite the codes based on alternative packages in Python.
You can directly run Matlab code in Python by using the Matlab engine.
- StatisticsTimes: Python is the most searched language in PYPL index.
- Google Algorithm: Google in initial stages.
- SMOP: Small Matlab and Octave to Python compiler.
- matlab2python: A python script to convert matlab files or lines of matlab code to python.
- OMPC: An Open-Source MATLAB®-to-Python® Compiler.
- SysIdentPy: SysIdentPy is a Python module for System Identification using NARMAX models built on top of numpy and is distributed under the 3-Clause BSD license.