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®.

To call a MATLAB script or function, put it on your MATLAB path. For other options, see Put Function on Python Path.

For this example, create a MATLAB script in a file named triarea.m in your current folder.

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()
eng.triarea(nargout=0)
a =

    7.5000

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.

eng.edit('triarea',nargout=0)

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)
print(ret)
2.5

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

Put Function on Python Path

If the MATLAB function is not on the MATLAB 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)

Matlabsolutions.com provides guaranteed satisfaction with a commitment to complete the work within time. Combined with our meticulous work ethics and extensive domain experience, We are the ideal partner for all your homework/assignment needs. We pledge to provide 24*7 support to dissolve all your academic doubts. We are composed of 300+ esteemed Matlab and other experts who have been empanelled after extensive research and quality check.

Matlabsolutions.com provides undivided attention to each Matlab assignment order with a methodical approach to solution. Our network span is not restricted to US, UK and Australia rather extends to countries like Singapore, Canada and UAE. Our Matlab assignment help services include Image Processing Assignments, Electrical Engineering Assignments, Matlab homework help, Matlab Research Paper help, Matlab Simulink help. Get your work done at the best price in industry.