开发者

How to get name of an enumeration in MATLAB

开发者 https://www.devze.com 2022-12-20 18:32 出处:网络
I define an enumerated type in MATLAB classdef(Enumeration) Color < Simulink.IntEnumType enumeration

I define an enumerated type in MATLAB

classdef(Enumeration) Color < Simulink.IntEnumType
  enumeration
    RED(0),
    GREEN(1),
    BLUE(2),
  end
end

I can assign it:

>> x = Color.RED    
x = 
    RED

I can display it like this:

>> disp(x)
    RED

or like this

>> x.display()
x =
    RED

How can I get access to that name ("R开发者_开发百科ED") as a string?

In other words I'm lookin for something like:

s = x.toString()

or

s = tostring(x)

both of which do not work.


You can use:

» str = char(Color.RED)
str =
RED
» class(str)
ans =
char

You can even override the default behaviour:

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

and now:

» char(Color.BLUE)
ans =
Color 2


A different approach, generic, in your calling entitiy:

strtrim(matlab.unittest.diagnostics.ConstraintDiagnostic.getDisplayableString(Color.BLUE))

This way you can save the class specific implementation of disp() and/or char().

0

精彩评论

暂无评论...
验证码 换一张
取 消