Using structures as enum input to a function in MATLAB

조회 수: 33 (최근 30일)
Jimmy cho
Jimmy cho 2020년 12월 22일
댓글: per isakson 2020년 12월 24일
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?!

답변 (1개)

Jan
Jan 2020년 12월 22일
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
Jan
Jan 2020년 12월 23일
@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 2020년 12월 24일
Why not
classdef colors < uint8
enumeration
Red (1)
Green (2)
end
end

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Enumerations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by