Main Content

matlab.engine.connect_matlab

Connect shared MATLAB session to MATLAB Engine for Python

Description

example

eng = matlab.engine.connect_matlab(name=None) connects to the shared MATLAB® session, name, and returns a MatlabEngine object as eng. The input argument name specifies the name of a MATLAB session that is already running on your local machine.

  • If you specify name and the engine cannot find a shared MATLAB session of the same name, then you receive an EngineError exception.

  • If you do not specify name and the engine cannot find any shared MATLAB sessions, then it starts a new shared MATLAB session.

  • If you do not specify name and the engine finds multiple shared MATLAB sessions running, then it connects to the first created session.

eng = matlab.engine.connect_matlab(___,background) connects asynchronously if background is True. You can use this syntax with the name input argument in the previous syntax.

eng = matlab.engine.connect_matlab(___,async) connects asynchronously if async is True. Not recommended. Use the background argument instead. Do not use for Python® Version 3.7. For more information, see Compatibility Considerations.

Examples

collapse all

Connect to a shared MATLAB session that is already running on your local machine.

import matlab.engine
eng = matlab.engine.connect_matlab()
eng.sqrt(4.0)
2.0

matlab.engine.connect_matlab connects to the first created shared MATLAB session. If no MATLAB sessions are shared, then matlab.engine.connect_matlab starts a new session.

When there are multiple shared MATLAB sessions on your local machine, connect to two different sessions one at a time by specifying their names.

Connect to the first created MATLAB session.

import matlab.engine
names = matlab.engine.find_matlab()
names
('MATLAB_6830', 'MATLAB_7090')

Connect to the next MATLAB session.

eng = matlab.engine.connect_matlab('MATLAB_7090')
eng.sqrt(4.0)
2.0

Input Arguments

collapse all

Name of the shared MATLAB session, specified as a character array.

Connect to MATLAB synchronously or asynchronously, specified as a logical keyword argument.

Example: matlab.engine.connect_matlab(background=True)

Connect to MATLAB synchronously or asynchronously, specified as a logical keyword argument.

Output Arguments

collapse all

Python variable for communicating with MATLAB, returned as a MatlabEngine object. eng communicates with a shared MATLAB session that is already running on your local machine

Limitations

  • Do not connect the engine multiple times to the same shared MATLAB session.

Compatibility Considerations

expand all

Introduced in R2015b