You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Simulink中通过MATLAB Function调用Python类的问题求助

问题描述

我计划在Simulink中开展仿真,控制器由Python编写,通过Simulink的MATLAB Function模块调用。此前仅用Python定义函数(def)时能成功获取结果,但定义类(class)后,无法在MATLAB Function中引用该类及类内函数。多数查阅案例都是Python调用MATLAB或调用Python函数,现附上简易模型说明、代码,寻求帮助。

相关代码及模型说明

Simulink模型

模型结构:输入模块连接到Interpreted MATLAB Function模块,输出连接到Scope模块。

Interpreted MATLAB Function代码

function out = RunPythonn(uu)
    in1=uu(1);
    in2=uu(2);
    coder.extrinsic('Example.py'); 
    controller=py.Example.Controller(in1,10);
    out=controller.test(in1,in2);
 end

Python代码(Example.py)

class Controller:
    def __init__(self,x1,time):
        self.time=time
        self.x1=x1

    def test(self,in1,in2):
        out=in1+in2+self.x1
        return out

需求

在Interpreted MATLAB Function中调用Python类及类内函数,且需在每个仿真时间步调用Python代码。


解决方案

针对在Simulink的MATLAB Function中调用Python类的问题,按以下步骤排查和修改:

1. 确保Python环境配置正确

  • 确认MATLAB已关联目标Python环境:在MATLAB命令行输入pyversion,检查输出的Python路径是否对应编写Example.py的环境。若路径错误,使用pyversion('你的Python安装路径')切换。
  • 将Example.py所在文件夹添加到MATLAB的Python搜索路径:在MATLAB命令行执行py.sys.path.append('Example.py所在文件夹的绝对路径'),或直接把该文件夹放到MATLAB当前工作目录下。

2. 修改MATLAB Function代码

原代码存在coder.extrinsic使用错误,修改后代码如下:

function out = RunPythonn(uu)
    % 声明需外部调用的Python类和方法
    coder.extrinsic('py.Example.Controller');
    coder.extrinsic('py.Example.Controller.test');
    
    in1 = uu(1);
    in2 = uu(2);
    
    % 创建Python类实例
    controller = py.Example.Controller(in1, 10);
    % 将Python返回值转换为MATLAB兼容的数值类型
    out = double(controller.test(in1, in2));
end
  • 注意:coder.extrinsic需指定Python类或方法的完整路径,而非.py文件名。
  • 调用类方法后,显式转换返回值类型(如double)可避免类型不兼容导致的仿真报错。

3. 处理类实例的状态延续(可选)

若控制器需要在时间步之间保持状态(如self.x1需持续更新),不能每个时间步都创建新实例,需用Persistent变量保存类实例:

function out = RunPythonn(uu)
    persistent controller; % 持久化变量,保留实例在时间步间不销毁
    
    coder.extrinsic('py.Example.Controller');
    coder.extrinsic('py.Example.Controller.test');
    
    in1 = uu(1);
    in2 = uu(2);
    
    % 仅首次调用时创建实例
    if isempty(controller)
        controller = py.Example.Controller(in1, 10);
    end
    
    % 按需更新实例属性
    controller.x1 = in1;
    controller.time = controller.time + 1; % 示例:时间步累加
    
    out = double(controller.test(in1, in2));
end

4. 仿真模式注意事项

  • 确保使用Interpreted Execution模式(你的模块已为Interpreted MATLAB Function,符合要求),若使用Code Generation模式,Python调用会受限。
  • 仿真前先在MATLAB命令行测试Python类调用:输入obj = py.Example.Controller(5,10); obj.test(2,3),验证是否返回正确结果(5+2+3=10)。若命令行报错,优先解决Python环境和路径问题。

内容的提问来源于stack exchange,提问作者Amy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 19:35:15