我正在使用 matlab 2016b,很高兴看到 Matlab 中有一些 python 支持 (https://uk.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html)
我想知道是否有办法将用户设计的 python 类暴露给 Matlab。所以,假设我有一个 python 类:
class MyPythonClass(object):
def __init__(self):
self.value = 5
def set_value(self, v):
self.value = v
这个简单的 python 类能否以某种方式在较新版本的 Matlab 中暴露给 Matlab?我看到了 python 支持,但没有提到任何 matlab 到 python 的桥接。
请您参考如下方法:
当然可以!我同意该部分的文档可能会稍微好一些,但无论如何。请注意,Python 支持自 MATLAB R2014b 起可用。因此,首先您应该检查 Python 是否可用并且您安装了正确的版本:
pyversion
接下来,创建一个包含您的测试类的 Python 文件/模块:
# MyTestModule.py
class MyPythonClass(object):
def __init__(self):
self.value = 5
def set_value(self, v):
self.value = v
非常重要的一步:我们必须将当前的MATLAB路径添加到Python路径中,这样Python才能找到你的模块。这记录在案 here :
if count(py.sys.path,'') == 0
insert(py.sys.path,int32(0),'');
end
现在我们已经准备好我们自己的 Python 类了!所有 Python 命令都以 py. 开头,因此我们使用
c = py.MyTestModule.MyPythonClass
显示
c =
Python MyPythonClass with properties:
value: 5
<MyTestModule.MyPythonClass object at 0x12b23cbd0>
我们的 Python 类可以像“普通”MATLAB 类一样使用:
>> c.set_value(10)
>> c.value
ans =
10
>> set_value(c,5)
>> c.value
ans =
5
