Marc February 2016

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?

  • I thought about redefining the "char()" function for myEnum, but that's not it - I don't want to end up with a frequency object.
  • I certainly could replace every use of [enumVariable with [char(enumVariable) - but I'm trying to avoid that work.

Answers


Daniel February 2016

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

Post Status

Asked in February 2016
Viewed 3,521 times
Voted 8
Answered 1 times

Search




Leave an answer