Install Matlab Engine API in Python

Related: Call Python from Matlab


Alternative: Call Matlab .m function code using free open-source GNU Octave from Python with oct2py.

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

Install

  1. find the directory Matlab is installed in by from Terminal / Command Prompt:

    matlab -batch matlabroot
  2. assuming Matlab root is like MATLAB/R2019a/ then do from Terminal / Command Prompt:

    cd MATLAB/R2019a/extern/engines/python
  3. This step depends on your operating system. From Terminal / Command Prompt:

    • Mac or Linux:

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

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

Permissions Error

If error about needing 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

Examples

Python → Matlab

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

eng.quit()

The Matlab Engine should take less than 1 second for Matlab Engine to start when called from Python.

matlab.double → Numpy

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

Python float → Matlab Engine

Python floats pass into Matlab Engine by including a period . after the number.

  • asin(1) fails
  • asin(1.) works

numpy.ndarray → Matlab Engine

Matlab Engine from Python can pass N-dimensional arrays.

Asynchronous Matlab Engine

Matlab Engine provides asynchronous call with background=True option  

Notes