查看单个帖子
旧 2019-12-10, 20:30   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 如何在MATLAB中获取枚举的名称

我在MATLAB中定义了枚举类型

classdef(Enumeration) Color < Simulink.IntEnumType enumeration RED(0), GREEN(1), BLUE(2), end end 我可以分配它:

>> x = Color.RED x = RED 我可以这样显示:

>> disp(x) RED 或像这样

>> x.display() x = RED 我如何以字符串形式访问该名称(“ RED”)?

换句话说,我正在寻找类似的东西:

s = x.toString() 要么

s = tostring(x) 两者都不起作用。



回答:

您可以使用:

禄 str = char(Color.RED) str = RED禄 class(str) ans = char 您甚至可以覆盖默认行为:

classdef(Enumeration) Color < int32 enumeration RED(0) GREEN(1) BLUE(2) end methods function s = char(obj) s = ['Color ' num2str(obj)]; %# or use a switch statement.. end function disp(obj) disp( char(obj) ) end end end 现在:

禄 char(Color.BLUE) ans = Color 2

更多&回答...
poster 当前离线   回复时引用此帖