简体   繁体   English

从matlab调用python

[英]Calling python from matlab

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 )我正在使用 matlab 2016b 并且很高兴看到 Matlab 中有一些 python 支持( 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.我想知道是否有办法将用户设计的 python 类公开给 Matlab。 So, say I have a python class:所以,假设我有一个 python 类:

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?在较新版本的 Matlab 中,这个简单的 Python 类能否以某种方式暴露给 Matlab? I see python support but no mention of any matlab to python bridge.我看到了 python 支持,但没有提到任何 matlab 到 python 桥。

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.请注意,自 MATLAB R2014b 以来,Python 支持已可用。 So, first you should check that Python is available and you have the correct version installed:所以,首先你应该检查 Python 是否可用并且你安装了正确的版本:

pyversion

Next, create a Python file/module which contains your test class:接下来,创建一个包含您的测试类的 Python 文件/模块:

# 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.非常重要的一步:我们必须将当前的 MATLAB 路径添加到 Python 路径中,这样 Python 才能找到您的模块。 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!现在我们准备好我们自己的 Python 类了! All Python commands start with py.所有 Python 命令都以py.开头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:并且我们的 Python 类可以像“普通”MATLAB 类一样使用:

>> c.set_value(10)
>> c.value
ans =
    10
>> set_value(c,5)
>> c.value
ans =
    5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM