This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Call User Scripts and Functions from Python

This example shows how to call a MATLAB® script to compute the area of a triangle from Python®.

In your current folder, create a MATLAB script in a file named triarea.m.

b = 5;
h = 3;
a = 0.5*(b.* h)

After you save the file, start Python and call the script.

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


Specify nargout=0. Although the script prints output, it returns no output arguments to Python.

Convert the script to a function and call the function from the engine. To edit the file, open the MATLAB editor.


Delete the three statements. Then add a function declaration and save the file.

function a = triarea(b,h)
a = 0.5*(b.* h);

Call the new triarea function from the engine.

ret = eng.triarea(1.0,5.0)

The triarea function returns only one output argument, so there is no need to specify nargout.

See Also


Related Topics