matlabenumsmatlab-class

How do I create enumerated types in MATLAB?


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


Solution

  • 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.