Marc
Marc

Reputation: 3313

Using Matlab Enumerations

Here is an edge case I've discovered to using Matlab enumerations. I'm converting some old code that used string inside a class to fulfill the functions of an enumeration to a proper enumeration. Now, as I convert that code I have many examples of this:

output = [enumVariable ' plus some text'];

(where enumVariable is of type myEnum): as I build up strings for errors, etc. However, since the enumerated variable is first, Matlab is trying to convert the resultant string into the myEnum type, giving me an error:

Cannot convert an object of class 'char' to enumeration class 'myEnum' because there is no conversion method available.

Is there some easy to get around this, or do I have to go change every usage?

Upvotes: 2

Views: 891

Answers (1)

Daniel
Daniel

Reputation: 36710

Your idea of overloading methods was the right idea, you simply tried it with the wrong method. You have to overload horzcat. Instead of overloading just this method, I recommend to implement vertcat and horzcat using cat and only reimplement this more generic method.

classdef myEnum
   enumeration
      Monday, Tuesday, Wednesday, Thursday, Friday
   end
   methods
       function c=cat(obj,d,varargin)
           if isa(varargin{1},class(obj)) %do not cast
               c=builtin('cat',d,obj,varargin{:});
           else %builtin cast
               obj2=cast(obj,class(varargin{1}));
               c=builtin('cat',d,obj2,varargin{:});
           end
       end
       function c=horzcat(obj,varargin)
           c=obj.cat(2,varargin{:});
       end
       function c=vertcat(obj,varargin)
           c=obj.cat(1,varargin{:});
       end

   end
end

a simple demonstration:

>> enumVariable=myEnum.Monday

enumVariable = 

    Monday   

>> [enumVariable ' plus some text']

ans =

Monday plus some text

Upvotes: 2

Related Questions