Reputation: 121077
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?
Upvotes: 9
Views: 5176
Reputation: 128
I know this question has been answered a long time ago, but I just found out about a different solution which can be pretty neat when using enums in an argument block. Also I couldn't find any reference to this feature in the official documentation so I thought I'd post it here:
The constructor for any enumeration can be called using an element name as sole argument. E.g.
>> Weekdays('Friday')
ans =
Weekdays enumeration
Friday
Ok, so we can omit the dot. But why is this interesting? Well, when using enums as a function argument, the argument block allows for automatic conversion from string/char to enumeration.
function test(day)
arguments
day Weekdays
end
day
end
.
>> test('Friday')
day =
Weekdays enumeration
Friday
Upvotes: 2
Reputation: 8937
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
Upvotes: 6
Reputation: 74940
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)
Upvotes: 5