Install Matlab Engine API in Python

Related: Call Python from Matlab

Alternative: If you don’t have Matlab, you can call Matlab .m function code using free open-source GNU Octave from Python with oct2py.


Matlab Engine API works from Python 3.6, 3.5, 3.4 and 2.7. That is, you can call Matlab functions from Python code!

Linux/Mac

cd $(dirname $(realpath $(which matlab)))/../extern/engines/python

python setup.py build --build-base=$(mktemp -d) install

Permissions Error

If you get a complaint about root permissions, you’re probably installing in system Python. I normally recommend using Anaconda Python instead, but if you must use system Python:

python setup.py build --build-base=$(mktemp -d) install --user

Windows

cd %PROGRAMFILES%/MATLAB/R2017b/extern/engines/python

python setup.py build --build-base=%TEMP% install

Matlab API from Python: Examples

Python program calling Matlab functions

import matlab.engine
eng = matlab.engine.start_matlab('-nojvm')
y=eng.asin(1.)

eng.quit()

The -nojvm Matlab Engine option is important for not having the Matlab Engine hang forever upon startup. It should take less than 1 second for Matlab Engine to start when called from Python.

Convert matlab.double arrays to Numpy arrays

enclose the matlab.double variable in numpy.asarray()

pass floats to Matlab Engine explicitly

by including a period ‘.’ after the number. e.g. asin(1) will fail, but asin(1.) will work.

pass N-D arrays (e.g. matrices) using the Matlab Engine

unlike the py module when using Matlab directly.  

References

Mathworks Matlab Engine

Matlab Engine in non-default locations

Leave a Comment