Skip to content

Instantly share code, notes, and snippets.

@rahulbhadani
Last active April 7, 2020 20:37
Show Gist options
  • Save rahulbhadani/925103b77dd7b0b32bacf90ee8ddcb28 to your computer and use it in GitHub Desktop.
Save rahulbhadani/925103b77dd7b0b32bacf90ee8ddcb28 to your computer and use it in GitHub Desktop.
How to use MATLAB Functionality from within Python

How to use MATLAB Functionality from within Python

Install MATLAB Engine for Python

  • Source your python environment. For me, it is anaconda with the name of virtual environment base.
source activate base
  • Change your directory to where you installed MATLAB
cd /usr/local/MATLAB/R2019a/extern/engines/python

Here, my MATLAB is installed in /usr/local/MATLAB/R2019a

  • Install matlab engine for python
python setup.py install

This will install matlab engine for python in your current python virtual environment

  • To test whether it works:
import matlab.engine

If the import is successful, you won't get any error message

An example use:

I have a matlab class in /home/ivory/VersionControl/Jmscslgroup/ROSBagReader. I want to use it from python. I will do it as follows:

eng = matlab.engine.start_matlab()
eng_return = eng.addpath('/home/ivory/VersionControl/Jmscslgroup/ROSBagReader')

In my case, I have a class in MATLAB called as ROSBagReader that takes an argument bagfile to instantiate the class object which I can use in python as follows:

BagReader = eng.ROSBagReader(bagfile)

References

  1. https://www.mathworks.com/help/matlab/matlab_external/matlab-arrays-as-python-variables.html
  2. https://www.mathworks.com/help/matlab/matlab_external/call-user-script-and-function-from-python.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment