Install Matlab Engine API in Python
Matlab Engine API allows calling Matlab functions from Python code.
These commands are executed from Terminal / PowerShell, not from Matlab. Go to the Matlab Engine directory:
cd $(matlab -batch "disp(matlabroot)")/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)
failsasin(1.)
works
Python can pass N-dimensional arrays to Matlab.
Matlab Engine provides asynchronous call with background=True
References:
Related:
- call Python from Matlab
- Alternative: call Matlab
.m
functions from Python using GNU Octave oct2py.