How do I create enumerated types in MATLAB?

40,332

Solution 1

You can get some of the functionality with new-style MATLAB classes:

classdef (Sealed) Colors
    properties (Constant)
        RED = 1;
        GREEN = 2;
        BLUE = 3;
    end

    methods (Access = private)    % private so that you cant instantiate
        function out = Colors
        end
    end
end

This isn't really a type, but since MATLAB is loosely typed, if you use integers, you can do things that approximate it:

line1 = Colors.RED;
...
if Colors.BLUE == line1
end

In this case, MATLAB "enums" are close to C-style enums - substitute syntax for integers.

With the careful use of static methods, you can even make MATLAB enums approach Ada's in sophistication, but unfortunately with clumsier syntax.

Solution 2

Starting from R2010b, MATLAB supports enumerations.

Example from the documentation:

classdef Colors
   properties
      R = 0;
      G = 0;
      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)
      Green (0, 1, 0)
      Blue  (0, 0, 1)
   end
end

Solution 3

If you want to do something similar to what Marc suggested, you could simply make a structure to represent your enumerated types instead of a whole new class:

colors = struct('RED', 1, 'GREEN', 2, 'BLUE', 3);

One benefit is that you can easily access structures in two different ways. You can specify a field directly using the field name:

a = colors.RED;

or you can use dynamic field names if you have the field name in a string:

a = colors.('RED');

In truth, there are a few benefits to doing what Marc suggested and creating a whole new class to represent an "enum" object:

  • You can control how the object is modified.
  • You can keep the definition in one place and easily use it in multiple places.
  • You can control failures and make them more "graceful", like returning an empty matrix if you try to access a non-existent field (as opposed to throwing an error).

However, if you don't need that sort of complexity and just need to do something quick, a structure is likely the easiest and most straight-forward implementation. It will also work with older versions of MATLAB that don't use the newest OOP framework.

Solution 4

There is actually a keyword in MATLAB R2009b called 'enumeration'. It seems to be undocumented, and I cannot say I know how to use it, but the functionality is probably there.

You can find it in matlabroot\toolbox\distcomp\examples\+examples

classdef(Enumeration) DmatFileMode < int32

    enumeration
        ReadMode(0)
        ReadCompatibilityMode(1)
        WriteMode(2)
    end
<snip>
end

Solution 5

You could also use Java enum classes from your Matlab code. Define them in Java and put them on your Matlab's javaclasspath.

// Java class definition
package test;
public enum ColorEnum {
    RED, GREEN, BLUE
}

You can reference them by name in M-code.

mycolor = test.ColorEnum.RED
if mycolor == test.ColorEnum.RED
    disp('got red');
else
    disp('got other color');
end

% Use ordinal() to get a primitive you can use in a switch statement
switch mycolor.ordinal
    case test.ColorEnum.BLUE.ordinal
        disp('blue');
    otherwise
        disp(sprintf('other color: %s', char(mycolor.toString())))
end

It won't catch comparisons to other types, though. And comparison to string has an odd return size.

>> test.ColorEnum.RED == 'GREEN'
ans =
     0
>> test.ColorEnum.RED == 'RED'
ans =
     1     1     1
Share:
40,332

Related videos on Youtube

iddober
Author by

iddober

Updated on September 21, 2020

Comments

  • iddober
    iddober over 3 years

    Are there enumerated types in MATLAB? If not, what are the alternatives?

  • Patrick O'Leary
    Patrick O'Leary about 14 years
    This is the correct way to do it if you will perform code generation. It is documented better in the Simulink documentation under "Defining an Enumerated Data Type."
  • Benjamin Oakes
    Benjamin Oakes almost 14 years
    Just be aware of possible performance hits when using the new object oriented stuff. In my experience, it introduced a significant overhead. It really depends on what you're doing, however.
  • Marc
    Marc almost 14 years
    Actually, for simple classes, there is effectively no time penalty compared to using lots of global structs. However, the development time savings for good practices is substantial, and rarely is runtime such a problem. Hardware's cheap. The people writing the software aren't.
  • Amro
    Amro over 11 years
    for future readers, this probably should be the accepted answer (all good solutions nonetheless)
  • James Mertz
    James Mertz about 11 years
    This is a more complicated example of the enum class. A simpler one can be found within the documentation.
  • JaBe
    JaBe over 9 years
    Url for the simpler example @KronoS mentioned: link
  • Marc
    Marc about 5 years
    See below for the Now-standard Enumeration keyword. That is the better answer now.