views:

186

answers:

2

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 ("RED") 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.

A: 

Lok at the related question:

http://stackoverflow.com/questions/1389042/how-do-i-create-enumerated-types-in-matlab

yuk
I'm not sure that question will help much with the problem of converting an enumerated type to a string the way the OP wants to do.
gnovice
+3  A: 

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
Amro
note: since I dont have simulink, I tested the above using the definition: `classdef(Enumeration) Color < int32`
Amro
Did you test what `str` actually was? I can't test it right now, but I think this might just convert the *integer representation* of the enumerated type to a `char` (i.e. `char(0)`).
gnovice
@gnovice: it is returning `"RED"` as expected
Amro
@Amro: Ah, good. Just checking. ;)
gnovice

related questions