Call MATLAB Functions from Python

Return Output Argument from MATLAB Function

You can call any MATLAB® function directly and return the results to Python®. For example, to determine if a number is prime, use the engine to call the isprime function.

import matlab.engine
eng = matlab.engine.start_matlab()
tf = eng.isprime(37)

Return Multiple Output Arguments from MATLAB Function

When you call a function with the engine, by default the engine returns a single output argument. If you know that the function can return multiple arguments, use the nargout argument to specify the number of output arguments.

To determine the greatest common denominator of two numbers, use the gcd function. Set nargout to return the three output arguments from gcd.

import matlab.engine
eng = matlab.engine.start_matlab()
t = eng.gcd(100.0,80.0,nargout=3)
(20.0, 1.0, -1.0)

Return No Output Arguments from MATLAB Function

Some MATLAB functions return no output arguments. If the function returns no arguments, set nargout to 0.

Open the MATLAB Help browser from Python.

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

The MATLAB doc function opens the browser, but does not return output arguments. If you do not specify nargout=0, the engine raises an error.

Stop Execution of Function

To stop execution of a MATLAB function press Ctrl+C. Control returns to Python.

See Also


Related Topics