Calling python from matlab
<p>I am using matlab 2016b and was excited to see that there is some python support in Matlab (<a href="https://uk.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html" rel="nofollow">https://uk.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html</a>)</p>

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

<pre><code>class MyPythonClass(object):
    def __init__(self):
        self.value = 5

    def set_value(self, v):
        self.value = v
</code></pre>

<p>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.  </p>

<p>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:</p>

<pre><code>pyversion
</code></pre>

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

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

    def set_value(self, v):
        self.value = v
</code></pre>

<p>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 <a href="https://mathworks.com/help/matlab/matlab_external/call-user-defined-custom-module.html" rel="nofollow">here</a>:</p>

<pre><code>if count(py.sys.path,'') == 0
    insert(py.sys.path,int32(0),'');
end
</code></pre>

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

<pre><code>c = py.MyTestModule.MyPythonClass
</code></pre>

<p>which shows</p>

<pre><code>c = 
  Python MyPythonClass with properties:
    value: 5
    &lt;MyTestModule.MyPythonClass object at 0x12b23cbd0&gt;
</code></pre>

<p>and our Python class can be used like a "normal" MATLAB class:</p>

<pre><code>&gt;&gt; c.set_value(10)
&gt;&gt; c.value
ans =
    10
&gt;&gt; set_value(c,5)
&gt;&gt; c.value
ans =
    5
</code></pre>

python matlab