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 aTriangle
handle object and call itsarea
method 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
Copytr
to the MATLAB workspace. You can useeval
to access the properties of a handle object from the workspace.
eng.workspace["wtr"] = tr b = eng.eval("wtr.Base") print(b)
5.0
改变高度thesetHeight
method. 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
Triangle
class objecttr
, is a handle to the object, not a copy of the object. If you createtr
in a function, it is only valid within the scope of the function.
See Also
matlab.engine.MatlabEngine
|matlab.engine.FutureResult