将 Python 代码与 Simulink 集成的概述
本主题概述 Python® 代码与 Simulink® 的集成。您可以设置系统以将 Python 与 Simulink 结合使用,并使用 MATLAB Function 模块或 MATLAB System 模块将 Python 代码与 Simulink 集成。
将系统配置为使用 Python
要调用 MATLAB® 中的 Python 模块,您必须安装兼容版本的 Python。有关支持的 Python 版本以及设置您的系统以在 MATLAB 中使用 Python 的详细信息,请参阅配置您的系统使用 Python。
您可以从 MATLAB 访问所有标准 Python 库、第三方功能或用户创建的模块。有关在 MATLAB 中使用 Python 的详细信息,请参阅从 MATLAB 访问 Python 模块 - 快速入门。
使用 MATLAB Function 模块将 Python 代码与 Simulink 代码集成
使用 MATLAB Function 模块将简单的 Python 代码与 Simulink 代码集成。使用 py. 作为 Python 函数或类名称的前缀来调用 MATLAB Function 模块中的 Python 模块。
以下代码实现一个 MATLAB Function 模块,它使用 py.math.cos 和 py.math.sin 计算所提供输入的复数的欧拉公式。
function [re, img, num] = euler(x) % Declare py.math.cos and py.math.sin as extrinsic functions coder.extrinsic('py.math.cos','py.math.sin'); % Preallocate outputs re = double(0); img = double(0); re = py.math.cos(x); img = py.math.sin(x); num = re + 1j*img; end
Python 模块不支持代码生成,需要 MATLAB 引擎才能执行。您可以从代码生成中排除 Python 调用,并使用 MATLAB 引擎来执行,方法是使用
coder.extrinsic函数将其声明为外部函数。以下代码将py.math.cos和py.math.sin声明为外部函数。coder.extrinsic('py.math.cos','py.math.sin');
外部函数在运行时返回的输出是
mxArray,也称为 MATLAB 数组。对 MATLAB 数组的有效操作仅限于将其存储在变量中、将其传递给另一个外部函数或将其返回到 MATLAB。要对mxArray值执行任何其他操作,例如在代码的表达式中使用它,您必须在运行时将mxArray转换为已知类型。要执行此操作,请将mxArray赋给变量,此变量的类型已由以前的赋值定义。有关预分配mxArray的更多详细信息,请参阅运行时返回外部函数的输出。以下代码将数值的实部和虚部的数据类型预分配为double。re = double(0); img = double(0);
在 Simulink 中实现 MATLAB Function 来计算输入的欧拉公式。

使用 MATLAB System 模块将 Python 代码与 Simulink 代码集成
您可以使用 MATLAB System 模块将 Python 代码与 Simulink 代码集成。当算法需要处理状态动态、流数据或其他模块自定义时,请使用此模块。您可以使用 py. 作为 Python 函数或类名称的前缀来调用 Python 模块。MATLAB System 模块中的 Python 函数调用不需要声明为外部函数。将仿真方式模块参数更改为 Interpreted Excecution。
以下代码实现一个 MATLAB System object™,后者调用 py.math.cos 和 py.math.sin 来计算复数的欧拉公式。
classdef eulerSystem < matlab.System % System object to calculate Euler's formula for an input methods (Access = protected) function [re, img, num] = stepImpl(obj, u) % Implement algorithm re = py.math.cos(u); img = py.math.sin(u); num = py.math.cos(u) + 1j*py.math.sin(u); end function [c1, c2, c3] = isOutputComplexImpl(obj) % Implement propagator to declare complexity of outputs c1 = false; c2 = false; c3 = true; end function [flag1, flag2, flag3] = isOutputFixedSizeImpl(obj) % Implement propagator to declare if outputs are fixed size flag1 = true; flag2 = true; flag3 = true; end function [sz_1, sz_2, sz_3] = getOutputSizeImpl(obj) % Implement propagator to declare output sizes sz_1 = [1,1]; sz_2 = [1,1]; sz_3 = [1,1]; end function [out_1, out_2, out_3] = getOutputDataTypeImpl(obj) % Implement propagator to declare output data types out_1 = "double"; out_2 = "double"; out_3 = "double"; end end end
如下所示,在 Simulink 中实现 System object 来计算输入的欧拉公式。

在模型编译期间,如果系统模块的输出设定无法从输入直接推断,则应定义传播器方法。上面的代码实现 isOutputComplexImpl、isOutputFixedSizeImpl、getOutputSizeImpl 和 getOutputDataTypeImpl 传播器方法。有关传播方法的详细信息,请参阅Add and Implement Propagation Methods。