Matlab中的类和枚举用法
例如:
classdef Enum_ChgBatState < Simulink.IntEnumType
enumeration
Enum_ChgBatState_Offline(0)
Enum_ChgBatState_Connect(1)
Enum_ChgBatState_Online(2)
Enum_ChgBatState_PreShutdown(3)
Enum_ChgBatState_Shutdown(4)
end
methods (Static)
function retVal = getHeaderFile()
retVal = ‘GlobalDefine.h’;
end
end
end
在汽车控制软件开发过程中,使用 Simulink建模时,经常会用到枚举型数据。因为枚举型数据在表示数据时有着更清晰的物理含义,模型及生成的代码的可读性更强。
Simulink中枚举型数据的定义
在simulink中,枚举型数据的定义有两种方法:
在M文件中用 classdef模块进行定义;
使用函数Simulink.defineIntEnumType定义。
1在M文件中用classdef模块进行定义
1.1.1 首先定义一个Simulnk.IntEnumType的之类,然后定义每个枚举值对应的数值。
例子如下:
例一:定义一个发动机状态的枚举类。
classdef Eng_State < Simulink.IntEnumType
enumeration
Stop (0)
Crank (1)
Run (2)
end
end
在simulink环境下使用枚举型数据时,要注意一下:
枚举类型数据的名称必须是唯一的,区分大小写,不能再workspace信号名称和数据类型名称有重复。
枚举值对应的数值必须是连续单调递增的,但是在定义的时候,对排序不做要求。
1.1.2 Simulink枚举类型的定制化
针对在仿真和代码生成时的特殊需求,可以在类的定义中用静态的方法对Simulink枚举类型数据的属性进行定制化。
静态的方法如下:
针对于例一的定义,Eng_State的默认值为Eng_State.Stop(默认为定义的第一个元素)。可以利用getDefaultValue方法指定默认值。Simulink.defineIntEnumType
例二:
classdef Eng_State <Simulink.IntEnumType
enumeration
Stop (0)
Crank (1)
Run (2)
end
methods (Static = true)
function retVal = getDefaultValue()
retVal = Eng_State.Run;
end
function retVal = getDescription ()
retVal = ‘ This is the state of the engine’;
end
function retVal = getHeadFile ()
retVal = ‘Eng_state.h’;
end
function retVal = getDataScope ()
retVal = ‘Exported’; % if itis Exported, it will generate the code and to be used by other component.
if it is Imported, it will generate the code and use the data defined byother component.
end
function retVal = addClassNametoEnumNames ()
retVal = ‘ true’;
end
end
end
1.1.3将文件保存为M类型的文件
将定义好的类保存为matlab文件:
文件的名称必须和类的名字一样。例如:上边的例子保存为Eng_State.m文件
保存的文件必须在matlab的添加的路径下, 这样使用时Matlab能自动找到这个定义。而且,使用时不用运行,直接放在matlab保存的路径下就可以了。
每个enum数据类型的定义必须要是单独的文件,不能再一个文件里面定义多个enum数据类型
2使用函数Simulink.defineIntEnumType定义
Simulink.defineIntEnumType函数也可以实现枚举类的定义
函数的用法如下:
例三如下:实现的功能和例2相同。
Simulink.defineIntEnumType(‘Eng_State’, …
{'Stop', 'Crank', 'Run'}, [0;1;2],...
'Description', ' This is the state of theengine ', ...
'DefaultValue', 'Run', ...
'HeaderFile', ' Eng_state.h ', ...
'DataScope',' Exported ', ...
'AddClassNameToEnumNames', true);
原文链接:https://blog.csdn.net/u011479862/article/details/78117788