How can I get rid of this enumeration error while using classes?

조회 수: 105 (최근 30일)
Oluwaseun
Oluwaseun 2013년 12월 10일
댓글: Captain Karnage 2023년 8월 7일
Here's an example of what I am trying to do:
classdef Colors
properties
R = 0;
G = O;
B = 0;
end
methods
function c = Colors(r , g, b)
c.R = r; c.G = g; c.B = b;
end
end
enumeration
Red (1, 0, 0)
Orange (1,.5, 0)
Yellow (1, 1, 0)
Green (0, 1, 0)
Blue (0, 0, 1)
Indigo (.2,0,.8)
Violet (1, 0, 1)
end
end
>> c = Colors.Red
??? Error using ==> Colors
Attempt to define enumeration without Enumeration class attribute in class 'Colors'.
  댓글 수: 1
Captain Karnage
Captain Karnage 2023년 8월 7일
Perhaps it's because it's an old question and something you did was not supported in R2013. But in R2022b your code now works, with one exception: You have G = O (the letter O) when it should be G = 0 (zero).

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

답변 (1개)

Bradley Stiritz
Bradley Stiritz 2014년 7월 4일
MATLAB enumeration definitions can't be nested within another classdef definition, as your code attempts to do. That would be very convenient & useful, but unfortunately isn't supported currently.
You need to define your enumeration as its own class in its own @-folder. Also, note that since you've supplied your own enumeration values, your class needs to inherit support for those values. However, your numeric vector values aren't specified properly; they need to be within brackets. Here's how your classdef would need to look.. (I'm only showing the first few rows)
classdef MyColors < double
enumeration
Red ([1, 0, 0])
Orange ([1,.5, 0])
Yellow ([1, 1, 0])
end
end
Unfortunately, when we try to use this, we find that vector values aren't allowed :(
>> MyColors.Red
In class 'MyColors', enumeration member named 'Red' must be scalar.
So you'll have to find a different way to implement your idea. I would suggest considering an ordinary classdef with constant properties, a la :
classdef MyColors
properties (Constant)
Red = [1, 0, 0];
Orange = [1,.5, 0];
Yellow = [1, 1, 0];
end
end
Now we get our desired results:
>> MyColors.Red
ans =
1 0 0
  댓글 수: 1
Zangdaarr
Zangdaarr 2016년 1월 20일
Matlab really has its own way to copy OOL which challenge all logic and common sense.

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

카테고리

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