I am trying to use an enumerated class to dictate behaviour in a switch statement in another class's constructor. So, what I have is the following:
From my enumerated class:
classdef(Enumeration) MyScheme
enumeration
Scheme1, Scheme2, Scheme3
end
end
and then the class that uses this:
classdef MyClass < handle
methods
function c = MyClass(scheme, varargin)
switch(scheme)
case MyScheme.Scheme1
% Do stuff with varargin
case MyScheme.Scheme2
% Do different stuff with varargin
case MyScheme.Scheme3
% Do yet something else with varargin
otherwise
err('Not a valid scheme');
end
end
end
end
However, no matter what scheme I pass in to the constructor, it just goes straight into the first case. When I add a breakpoint and step through and manually check equality (scheme == MyScheme.Scheme1), it recognizes that the two are not equal and returns 0 for this check, so I do not understand at all why it would still enter first case. If I change the order of the cases it will just enter whichever one is first. As far as I can tell, this is identical syntax to the Using Enumerations in a Switch Statement section of this MATLAB help document, but perhaps I am missing something obvious?
I cannot reproduce the problem in R2013a:
classdef MyScheme
enumeration
Scheme1, Scheme2, Scheme3
end
end
classdef MyClass < handle
properties
x
end
methods
function obj = MyClass(scheme)
switch(scheme)
case MyScheme.Scheme1
obj.x = 10;
case MyScheme.Scheme2
obj.x = 20;
case MyScheme.Scheme3
obj.x = 30;
otherwise
error('Not a valid scheme');
end
end
end
end
which is working correctly:
>> MyClass(MyScheme.Scheme2)
ans =
MyClass with properties:
x: 20
If for some reason it is still not working for you, a workaround would be to compare their string representation instead:
switch char(scheme)
case char(MyScheme.Scheme1)
obj.x = 10;
case char(MyScheme.Scheme2)
obj.x = 20;
case char(MyScheme.Scheme3)
obj.x = 30;
otherwise
error('Not a valid scheme');
end
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