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します。関数でローカルに定義し、それを使用して関数内のステートメントの流れを制御したいと思います。REDBLUEcolors

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 に答える