Main Content

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 模块和示例所需的模块。打开模型。

MATLAB Function 模块进行编程

为模块编程,以计算值向量的均值和标准差。

  1. 双击 MATLAB Function 模块以打开 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.

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

    function [mean, stdev] = stats(vals)
    

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

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

    % 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.

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

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

  5. 完成与 MATLAB Function 模块的连接。

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

  6. 将模型另存为 call_stats_block2

检查 MATLAB Function 模块变量的属性

您可以检查和管理 MATLAB Function 模块中变量的属性。在此示例中,验证输入参量 vals 是否继承其类型和大小属性:

  1. 双击 MATLAB Function 模块。

  2. 打开符号窗格和属性检查器。在函数选项卡中,点击编辑数据

    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 分配给输出端口。如果您更改任一变量的类型条目,函数声明语句也会随之更改。

  3. 检查 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 模块中创建变量和设置属性的详细信息,请参阅。

对模型进行仿真

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

This shows connected signals between the blocks and the simulation results in the Display blocks.

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

This shows a plot of the input values and a line drawn through the values.

另请参阅

| |

相关主题

外部网站