【问题标题】:Defining enumerations and constants locally in MATLAB在 MATLAB 中本地定义枚举和常量
【发布时间】:2011-10-28 15:10:05
【问题描述】:

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

我看到 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:

我被问到一个例子,这里是 pseudocode 中的一个。这个例子描述了我定义和使用本地枚举的需要。

假设我有一个名为colors 的枚举类型,它可以是REDBLUE。我想在我的函数中本地定义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 代码来做到这一点吗?如果有,怎么做?

【问题讨论】:

  • 你能发布一个你想要的例子吗?

标签: matlab matlab-class


【解决方案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
    

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    相关资源
    最近更新 更多