从Matlab调用python [英] Calling python from matlab

查看:103
本文介绍了从Matlab调用python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matlab 2016b,很高兴看到Matlab中有一些python支持(

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)

我想知道是否有一种方法可以将用户设计的python类公开给Matlab.所以,说我有一个python类:

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

这个简单的python类可以以某种方式在Matlab的较新版本中公开吗?我看到了对python的支持,但没有提及任何matlab到python的桥梁.

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.

推荐答案

是的!我同意该文档在这方面可能会稍好一些,但是无论如何.请注意,自MATLAB R2014b开始提供Python支持.因此,首先,您应该检查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. So, first you should check that Python is available and you have the correct version installed:

pyversion

接下来,创建一个包含测试类的Python文件/模块:

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

非常重要的一步:我们必须将当前的MATLAB路径添加到Python路径,以便Python可以找到您的模块. 此处:

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

现在我们准备好自己的Python类了!所有Python命令均以py.开头,因此我们使用

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

其中显示

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

和我们的Python类可以像普通" MATLAB类一样使用:

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

这篇关于从Matlab调用python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆