登录论坛

查看完整版本 : 如何在MATLAB中获取枚举的名称


poster
2019-12-10, 20:30
我在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

更多&回答... (https://stackoverflow.com/questions/2312774)