枚举
要生成枚举数据类型,请在 MATLAB® 文件中定义枚举类。然后,使用该枚举类作为模型中信号、模块参数和状态的数据类型。
C 构造
typedef enum {
Choice1 = 0,
Choice2
} myEnumType;
过程
在当前文件夹中,创建 MATLAB 文件 ex_myEnumType.m。该文件定义枚举类 ex_myEnumType。
classdef ex_myEnumType < Simulink.IntEnumType enumeration Choice1(0) Choice2(1) end %enumeration methods (Static) function retVal = getHeaderFile() retVal = 'myEnumHdr.h'; end %function function retVal = getDataScope() retVal = 'Exported'; end %function end %methods end %classdef
1.打开模型 ex_pattern_enum,它有一个 Enumerated Constant 模块和一个 Multiport Switch 模块。

2.在模型数据编辑器中,选择参数选项卡。
3.在模型中,点击 Enumerated Constant 模块。
4.在模型数据编辑器中,使用值列将常量值设置为 myChoice。在 myChoice 旁边,点击操作按钮(含三个纵点),然后选择创建。
5.在“创建新数据”对话框中,将值设置为 Simulink.Parameter(ex_myEnumType.Choice1),然后点击创建。名为 myChoice 的 Simulink.Parameter 对象出现在基础工作区中。该对象存储 ex_myEnumType 类型的枚举值 Choice1。
6.在代码生成选项卡上,将存储类设置为 ExportedGlobal。使用此设置时,对象在生成的代码中作为全局变量出现。
7.在模型数据编辑器中,选择信号选项卡。
8.在模型中,选择 Enumerated Constant 模块的输出信号。
9.在模型数据编辑器中,使用数据类型列将信号数据类型设置为 Enum: ex_myEnumType。
10.选择 Multiport Switch 模块。
11.在属性检查器中,进行如下设置:
将数据端口顺序设置为
Specify indices。将数据端口索引设置为
enumeration('ex_myEnumType')。此表达式返回ex_myEnumType的所有枚举成员。
12.将模型配置参数文件打包格式设置为 Modular。使用此设置时,在生成的代码中,ex_myEnumType 的定义可以出现在指定的头文件 myEnumHdr.h 中。
13.要编译模型并生成代码,请按 Ctrl+B。
结果
查看生成的头文件 myEnumHdr.h。该文件定义枚举数据类型。
typedef enum {
Choice1 = 0, /* Default value */
Choice2
} ex_myEnumType;
查看源文件 ex_pattern_enum.c。该文件定义变量 myChoice。step 函数中的算法使用 myChoice 将其中一个输入信号传送到输出信号。
ex_myEnumType myChoice = Choice1; /* Variable: myChoice
/* Model step function */
void ex_pattern_enum_step(void)
{
/* MultiPortSwitch: '<Root>/Multiport Switch' incorporates:
* Constant: '<S1>/Constant'
*/
if (myChoice == Choice1) {
/* Outport: '<Root>/Data Out' incorporates:
* Inport: '<Root>/Data In 1'
*/
rtY.DataOut = rtU.DataIn1;
} else {
/* Outport: '<Root>/Data Out' incorporates:
* Inport: '<Root>/Data In 2'
*/
rtY.DataOut = rtU.DataIn2;
}
/* End of MultiPortSwitch: '<Root>/Multiport Switch' */
}