Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert strings to enumerations?

Tags:

enums

matlab

To convert an enumeration to be a character array is straightforward – you just call char.

char(myenum.somevalue)

returns 'somevalue'.

How do convert back again? I was expecting something like char2enum where

char2enum('somevalue', 'myenum')

returns myenum.somevalue.

Is there a builtin function for this or must I create my own?

like image 818
Richie Cotton Avatar asked Dec 22 '10 16:12

Richie Cotton


2 Answers

Creating an enum from a character is also fairly straightforward: Just create the enumeration:

out = myenum.somevalue

returns out with class myenum and value somevalue.

If your string is in a variable, call

someVariable = somevalue;
out = myenum.(someVariable)
like image 194
Jonas Avatar answered Oct 04 '22 00:10

Jonas


You can use MATLAB Dynamic reference feature to access the enumeration by its name as a string instead of its symbolic name. For example, given a class Weekdays

classdef Weekdays
   enumeration
    Monday, Tuesday, Wednesday, Thursday, Friday
   end
end

You can access the Friday type in a couple of ways:

>> Weekdays.Friday  % Access symbolically

>> Weekdays.('Friday') % Access as a string

If you have a string variable with the name of the class that works too:

>> day = 'Friday'
>> Weekdays.(day)

BTW, this feature works for MATLAB Class methods, properties, and events, as well as struct fields.

http://www.mathworks.com/help/matlab/matlab_prog/bsgigzp-1.html#bsgigzp-33

like image 30
Nick Haddad Avatar answered Oct 03 '22 23:10

Nick Haddad