Main Content

Start and Stop MATLAB Engine for Python

Start MATLAB Engine for Python

  • Start Python® at the operating system prompt.

  • Import the matlab.engine package into your Python session.

  • Start a new MATLAB® process by calling start_matlab. The start_matlab function returns a Python object eng which enables you to pass data and call functions executed by MATLAB.

import matlab.engine
eng = matlab.engine.start_matlab()

Start Engine with Startup Options

Start the engine and pass the options as an input argument string to matlab.engine.start_matlab. For example, start MATLAB with the desktop.

eng = matlab.engine.start_matlab("-desktop")

You can define multiple startup options with a single string. For example, start the desktop and set the numeric display format to short.

eng = matlab.engine.start_matlab("-desktop -r 'format short'")

You also can start the desktop after you start the engine.

import matlab.engine
eng = matlab.engine.start_matlab()
eng.desktop(nargout=0)

Start Specific MATLAB Engine Version

To start a specific version of the MATLAB engine, set the PYTHONPATH environment variable to the location of the package. This code assumes you used the setup shown in the previous section. To set PYTHONPATH on Windows to call MATLAB R2019b, type:

sys.path.append("c:\work\matlab19bPy36")

On Linux® or macOS:

sys.path.append("/local/work/matlab19bPy36")

To check which version of MATLAB was imported, in Python type:

import matlab
print(matlab.__file__)

Python might use different folder names for installation. For example, Python might create a subfolder lib/site-packages before installing the MATLAB engine. Verify the folder on your system to use with the sys.path.append command.

Start Engine Asynchronously

Start the engine asynchronously. While MATLAB starts, you can enter commands at the Python command line.

import matlab.engine
future = matlab.engine.start_matlab(background=True)

Create the MATLAB instance so you can perform computations in MATLAB.

eng = future.result()

Run Multiple Engines

Start each engine separately. Each engine starts and communicates with its own MATLAB process.

eng1 = matlab.engine.start_matlab()
eng2 = matlab.engine.start_matlab()

Stop Engine

Call either the exit or the quit function.

eng.quit()

If you exit Python with an engine still running, then Python automatically stops the engine and its MATLAB process.

See Also

Related Topics