How do I create enumerated types in MATLAB?

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

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

10条回答
  •  时光说笑
    2020-12-02 17:29

    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
    

提交回复
热议问题