Using structures as enum input to a function in MATLAB

28 views (last 30 days)
Hello
I'm implementing a function that gets as one input with two possible values Red (enum configured as 1) , Green(enum configured as 2).
so what I did in matlab is this:
colors = struct('Red', 1, 'Green', 2);
function output=choose(colors)
{
if (colors == Red) %in other words if I input 'Red' to function choose
do something
else (colors == Green )%in other words if input is 'Green' to function choose
do something
}
So I want to write this, choose (Red) or choose(Green) and get the required output of a function. this means I want to write in my editor after building the function just this : choose(Red) or choose (Green) then I get output.
How I can implement that in matlab? as I showed above it tells me once I write choose(Red) that Red isn't defined although I already defined it as structure above the function... any help?!

Answers (1)

Jan
Jan on 22 Dec 2020
You have defined a struct, but this is not an enum. With your code (if you omit the curly braces), you could use:
choose(colors.Red)
becaus your have created a struct. Matlab cannot guess, that you want to treat the field names for another purpose.
You need to defined an enumeration class for an enumeration: doc enumeration
Even then you need to sepcify the enumeration class in addition and choose(Red) is not possible:
classdef colors
enumeration
Red, Green
end
end
choose(colors.Red)
  7 Comments
Jan
Jan on 23 Dec 2020
@Jimmy cho: I strongly recommend not to do that and I do not believe that this is a clean programming style, but it works easily:
Insert in each function, which uses the variables, these lines:
Red = 1;
Green = 2;
Alternatively create a script, which contains these lines und call it from each function before the variables are used. Then you have to change only one code, if you add a new color. Remember, that this can slow down the processing massively, because the JIT-accelerator might not know the type of the concerned variables. Therefore I'd never use a script for anything.
The clean way is to define an enumeration class and "color.red" instead of "Red". I cannot imagine, why this clean and efficient method does not satisfy your needs and why choose(Red) is so much better then e.g. choose('red') .
per isakson
per isakson on 24 Dec 2020
Why not
classdef colors < uint8
enumeration
Red (1)
Green (2)
end
end

Sign in to comment.

Categories

Find more on Enumerations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!