How do I create enumerated types in MATLAB?

前端 未结 10 2168
不知归路
不知归路 2020-12-02 17:04

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

10条回答
  •  我在风中等你
    2020-12-02 17:24

    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.

提交回复
热议问题