Main Content

Call MATLAB Functions from Python

Use MATLAB® Engine API for Python® to call any MATLAB function on the MATLAB path.

If the MATLAB function is not on the path, you can call it from the current folder. For example, to call MATLAB function myFnc in folder myFolder, type:

import matlab.engine
eng = matlab.engine.start_matlab()
eng.cd(r'myFolder', nargout=0)
eng.myFnc()

If myFnc is in folder C:/work/myfiles, you can add this folder to the Python path.

eng.addpath("C:/work/myfiles")

To add a path to all subfolders, type:

s = eng.genpath('C:/work/myfiles')
eng.addpath(s, nargout=0)

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)
print(tf)
True

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)
print(t)
(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 MathWorks® documentation in your system web browser from Python.

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

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.

Use Function Names for MATLAB Operators

You can use a MATLAB operator in Python by calling the equivalent function. For a list of operators and associated function names, see MATLAB Operators and Associated Functions. For example, to add two numbers, use the plus function instead of the + operator.

import matlab.engine
eng = matlab.engine.start_matlab()
a = 2
b = 3
eng.plus(a,b) 

See Also

|

Related Topics