Install Matlab Engine API in Python

Matlab Engine API allows calling Matlab functions from Python code.

These commands are executed from Terminal, not from Matlab. Go to the Matlab Engine directory:

r=$(matlab -batch "disp(matlabroot)" | tail -n1)

cd ${r}/extern/engines/python

Setup Matlab Engine, where “python” starts the desired Python executable.

  • macOS or Linux:

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

    python setup.py build --build-base=$env:temp install --user

Root / admin permissions are NOT needed.


A simple example of using Matlab from Python:

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

eng.quit()

The Matlab Engine should take about 1 second for Matlab Engine to start when called from Python. For Matlab functions requiring JVM remove the “-nojvm” option.

Many Matlab numeric classes (single, double, logical) can be converted to Python types like:

numpy.asarray(x)

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

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

Python can pass N-dimensional arrays to Matlab.

Matlab Engine provides asynchronous call with background=True


References:

Related: