Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of an enumeration in MATLAB

Tags:

oop

enums

matlab

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.

like image 359
Philipp Avatar asked Feb 22 '10 17:02

Philipp


People also ask

Does MATLAB have enum?

Starting from R2010b, MATLAB supports enumerations. This is a more complicated example of the enum class. A simpler one can be found within the documentation.

What is a Classdef in MATLAB?

What Is a Class Definition. A MATLAB® class definition is a template whose purpose is to provide a description of all the elements that are common to all instances of the class. Class members are the properties, methods, and events that define the class.

What are enum types?

Enumerated (enum) types are data types that comprise a static, ordered set of values. They are equivalent to the enum types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status values for a piece of data.


1 Answers

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
like image 98
Amro Avatar answered Nov 15 '22 10:11

Amro