Documentation

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.

Use MATLAB Handle Objects in Python

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 named Triangle.m.

classdef Triangle < handle
    properties (SetAccess = private)
        Base = 0;
        Height = 0;
    end
    
    methods
        function TR = Triangle(b,h)
            TR.Base = b;
            TR.Height = h;
        end
        
        function a = area(TR)
            a = 0.5 .* TR.Base .* TR.Height;
        end
        
        function setBase(TR,b)
            TR.Base = b;
        end
        
        function setHeight(TR,h)
            TR.Height = h;
        end
    end
end

Start Python. Create a Triangle handle object and call its area 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

Copy tr to the MATLAB workspace. You can use eval to access the properties of a handle object from the workspace.

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

Change the height with the setHeight 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 object tr, is a handle to the object, not a copy of the object. If you create tr in a function, it is only valid within the scope of the function.

See Also

|

Related Topics

Was this topic helpful?