Main Content

UseMATLABHandle Objects inPython

This example shows how to create an object from a MATLAB®handle class and call its methods in Python®.

In your current folder, create a MATLAB handle class in a file namedTriangle.m.

classdefTriangle < handleproperties(SetAccess = private) Base = 0; Height = 0;endmethodsfunctionTR = Triangle(b,h) TR.Base = b; TR.Height = h;endfunctiona = area(TR) a = 0.5 .* TR.Base .* TR.Height;endfunctionsetBase(TR,b) TR.Base = b;endfunctionsetHeight(TR,h) TR.Height = h;endendend

Start Python. Create aTrianglehandle object and call itsareamethod with the engine. Pass the handle object as the first positional argument.

import matlab.engine eng = matlab.engine.start_matlab() tr = eng.Triangle(5.0,3.0) a = eng.area(tr) print(a)
7.5

Copytrto the MATLAB workspace. You can useevalto access the properties of a handle object from the workspace.

eng.workspace["wtr"] = tr b = eng.eval("wtr.Base") print(b)
5.0

改变高度thesetHeightmethod. If your MATLAB handle class defines get and set methods for properties, you can access properties without using the MATLAB workspace.

eng.setHeight(tr,8.0,nargout=0) a = eng.area(tr) print(a)
20.0

Note

Triangleclass objecttr, is a handle to the object, not a copy of the object. If you createtrin a function, it is only valid within the scope of the function.

See Also

|

Related Topics