主要内容

使用 MATLAB Function 模块在 Simulink 中实现 MATLAB 函数

MATLAB Function 模块使您能够使用 MATLAB® 代码在 Simulink® 模型中定义自定义函数。在以下情况下使用这些模块:

  • 您有现有 MATLAB 函数可用于对自定义功能进行建模,或您可以轻松创建这样的函数。

  • 您的模型需要在 Simulink 图形语言中没有或无法捕获的自定义功能。

  • 您发现使用 MATLAB 函数对自定义功能建模比通过使用 Simulink 模块图建模更容易。

  • 要建模的自定义功能不包括连续或离散的动态状态。要对动态状态建模,请使用 S-Function。请参阅使用 MATLAB S-Function 创建模块

使用 MATLAB Function 模块计算均值和标准差

此示例从包含 MATLAB Function 模块的模型开始,并指导您如何自定义该模块来计算值向量的均值和标准差。打开 call_stats_block1 模型以查看起始模块。模型包括一个空的 MATLAB Function 模块和示例所需的模块。

The starting model. The model contains a MATLAB Function block in the center, a Constant block that has a vector with four values to the left, and two Display blocks to the right. The blocks are not connected.

MATLAB Function 模块编程

为模块编程,以计算值向量的均值和标准差。要打开 MATLAB Function Block Editor,请双击 MATLAB Function 模块。MATLAB Function 模块编辑器中出现一个默认函数,其中有两个变量:一个输入参量和一个输出参量。

This image shows the MATLAB Function Block Editor after it has been opened from the call_stats_block1 model. It includes a default function.

通过编辑函数声明语句定义函数输入和输出:

function [mean, stdev] = stats(vals)

此语句定义一个名为 stats 的函数,该函数包含三个变量。该语句定义一个输入参量 vals 以及两个输出参量 meanstdev

在函数声明语句后的新行中,清除现有代码并添加以下代码:

% Calculates a statistical mean and a standard
% deviation for the values in vals.

len = length(vals);
mean = avg(vals,len);
stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len);
plot(vals,"-+");

function mean = avg(array,size)
mean = sum(array)/size;

最终的代码看起来是这样的:

The MATLAB Function Block Editor showing the final version of the code. It includes the code from the previous steps.

退出模块。该模块会更新端口名称。函数输出 meanstdev 对应于模块输出端口 meanstdev,函数输入 vals 对应于模块输入端口 vals

This shows the outline of the block without connections between the blocks.

完成与 MATLAB Function 模块的连接。

This shows the connected signals between the blocks established in the previous image.

保存模型。要查看此模型的完整版本,请打开 call_stats_block2 模型。

检查 MATLAB Function 模块变量的属性

您可以检查和管理 MATLAB Function 模块中变量的属性。在此示例中,验证输入参量 vals 是否继承其类型和大小属性。双击 MATLAB Function 模块。打开符号窗格和属性检查器。在函数选项卡中,点击编辑数据

The Function tab in the Simulink Editor while the MATLAB Function block Editor is open. The Edit Data button on the left is enclosed in a red box.

符号窗格在名称列中显示变量名称。类型列确定函数参量端口分配以及它在函数声明语句中出现的位置。在此示例中,vals 分配给输入端口。meanstdev 分配给输出端口。如果您更改任一变量的类型条目,函数声明语句也会随之更改。

检查 vals 的属性。在符号窗格中,点击 vals 对应的行。属性检查器会更新以显示 vals 的属性。作用域属性与类型列匹配。

The Property Inspector and the Symbols pane. The vals input variable is selected, and the Property Inspector displays the variable properties.

有关在 MATLAB Function 模块中创建变量和设置属性的详细信息,请参阅Create and Define MATLAB Function Block Variables

对模型进行仿真

在 Simulink 中,点击运行以仿真模型。该模型将数据从函数输出到两个 Display 模块。

The Display blocks show the simulation results of the model. The first Display block shows 3.5 and the second shows 1.118.

该模块还在单独的窗口中绘制输入数据。

A plot of the input values and a line drawn through the values. The line is blue.

另请参阅

| |

主题

外部网站