Main Content

在 System object 中使用全局变量

全局变量为您可以在其他 MATLAB® 函数或 Simulink® 模块中访问的变量。

MATLAB 中的 System object 全局变量

对于仅在 MATLAB 中使用的 System object,在 System object™ 类定义文件中定义全局变量的方式与在其他 MATLAB 代码中定义全局变量的方式相同(请参阅全局变量)。

Simulink 中的 System object 全局变量

对于 Simulink 的 MATLAB System 模块中使用的 System object,您也可以像在 MATLAB 中一样定义全局变量。但是,要在 Simulink 中使用全局变量,您必须在 stepImplupdateImploutputImpl 方法中声明全局变量(如果您已分别在 stepImplupdateImploutputImpl 调用的方法中对全局变量进行了声明)。

MATLAB System 模块设置和使用全局变量的方式与对 MATLAB Function 模块的方式相同(请参阅数据存储 (Simulink)在 MATLAB Function 模块中使用全局数据 (Simulink))。与 MATLAB Function 模块一样,您也必须使用与 Data Store Memory 模块匹配的变量名称,才能在 Simulink 中使用全局变量。

例如,以下类定义文件定义了一个 System object,该对象在每个时间步将矩阵的第一行增加 1。如果类文件采用 P 代码编码,则您必须包含 getGlobalNamesImpl

classdef GlobalSysObjMatrix < matlab.System
   methods (Access = protected)
      function y = stepImpl(obj)
         global B;
         B(1,:) = B(1,:)+1;
         y = B;
      end

      % Include getGlobalNamesImpl only if the class file is P-coded.
      function globalNames = getGlobalNamesImpl(~)
         globalNames = {"B"};
      end
   end
end
此模型将 GlobalSysObjMatrix 对象包含在 MATLAB System 模块和关联的 Data Store Memory 模块中。

This image shows a model with a system object named GlobalSysObjMatrix that reads data from a datastore and writes a single output to a scope block and outport block

Main tab of the block parameters

Signal attributes tab of the block parameters