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?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With