2

I am using matlab 2016b and was excited to see that there is some python support in Matlab (https://uk.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html)

I was wondering if there is a way to expose user-designed python classes to Matlab. So, say I have a python class:

class MyPythonClass(object):
    def __init__(self):
        self.value = 5

    def set_value(self, v):
        self.value = v

Could this simple python class be somehow exposed to Matlab in the newer versions of Matlab? I see python support but no mention of any matlab to python bridge.

1 Answer 1

2

Yes sure! I agree that the documentation could be slightly better in that part, but anyways. Note that Python support has been available since MATLAB R2014b. So, first you should check that Python is available and you have the correct version installed:

pyversion

Next, create a Python file/module which contains your test class:

# MyTestModule.py
class MyPythonClass(object):
    def __init__(self):
        self.value = 5

    def set_value(self, v):
        self.value = v

A very important step: we have to add the current MATLAB path to the Python path, so Python can find your module. This is documented here:

if count(py.sys.path,'') == 0
    insert(py.sys.path,int32(0),'');
end

Now we're ready to our own Python class! All Python commands start with py., so we create an instance of our class with

c = py.MyTestModule.MyPythonClass

which shows

c = 
  Python MyPythonClass with properties:
    value: 5
    <MyTestModule.MyPythonClass object at 0x12b23cbd0>

and our Python class can be used like a "normal" MATLAB class:

>> c.set_value(10)
>> c.value
ans =
    10
>> set_value(c,5)
>> c.value
ans =
    5
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.