1

我想在函数范围内本地定义枚举和常量。

我看到 MATLAB 提供枚举和常量作为其面向对象编程框架的一部分。但是,如果您尝试在函数范围内定义它们,它们将不起作用。例如,如果您尝试以下操作,MATLAB 会抱怨“解析错误:无效语法”:

function output = my_function(input)

classdef my_constants
  properties (Constant)
    x = 0.2;
    y = 0.4;
    z = 0.5;
  end
end

classdef colors
  enumeration
    blue, red
  end
end

statements;

原因似乎是每个都classdef需要在自己的.m文件中定义。

我想避免.m为我使用的每个枚举或一组常量创建一个文件。有没有办法做到这一点?我有哪些选择?

附录 1:

正因为有人问我一个例子,这里是一个伪代码。这个例子描述了我定义和使用本地枚举的需要。

假设我有一个枚举类型colors,它可以是REDor BLUE。我想colors在我的函数中本地定义,并使用它来控制我在函数中的语句流:

function output = my_function(input)

# ....
# Code that defines the enumeration 'colors'
#....

my_color = colors;

# ... code that changes 'my_color' ...

switch my_color
   case RED
       do this
   case BLUE
       do that;

end

附录 2:

我可以通过利用 Java 代码来做到这一点吗?如果是这样,怎么做?

4

1 回答 1

1

我认为枚举将是矫枉过正。你可以这样做

  • 定义 RGB 值的 matlab 结构
  • 确定“输入”哪种颜色并记住该颜色字段名
  • 用那种颜色做某事

    function output = my_function(input)
    
    % Code that defines the enumeration 'colors' in terms of RGB
    
    colors.RED = [1 0 0];
    colors.BLUE = [0 0 1]
    
    ... etc ... 
    
    
    
    % ... here... what determine my_color is, 
    % which is logic specific to your function
    % 
    % You should assign 'my_color' to the same struct
    % fieldname used in the above 'colors' 
    
    if( some red conditon )
    
       my_color = 'RED';
    
    elseif( some blue condition)
       my_color = 'BLUE';
    
    elseif(etc...)
    
    end
    
    
    % at this point, my_color will be a fieldname 
    % of the 'colors' struct.
    % 
    % You are able to dynamically extract the 
    % RGB value from the 'colors' struct using 
    % what is called called dynamic field reference.
    %
    % This means...
    % 
    % While you can hardcode blue like this:
    %
    %   colorsStruct.BLUE
    %
    % You are also able to dynamically get BLUE like this: 
    %
    %   colorName = 'BLUE';
    %   rgbValue = colorsStruct.(colorName);
    % 
    %
    % Loren has a good blog on this:
    %
    %   http://blogs.mathworks.com/loren/2005/12/13/use-dynamic-field-references/
    
    
    
    % Extract the rgb value
    my_color_rgb_value = colors.(my_color);
    
    
    % Do something with the RGB value
    your_specific_function(my_color_rgb_value);
    
    
    end
    

希望这可以帮助。如果没有,请发布跟进。

于 2011-11-09T06:26:37.963 回答