2016-07-30 7 views
1

MATLAB OOPを使用しようとしています。クラスコンストラクタのクラスメソッドハンドラを変更したいと思います。 例えば、I、クラスメソッドはクラスのプロパティの変数numberに応じてのいずれかの方法を使用するクラスtestを有する:ここMATLABクラス定義メソッドのハンドラを変更することは可能ですか?

mytest = test(2); 
mytest.somemethod(); 

classdef test < handle 
    properties 
    number 
    end 
    methods   
    function obj = test(number) 
     obj.number = number; 
    end 
    function obj = somemethod(obj) 
     switch obj.number 
     case 1 
      obj.somemethod1(); 
     case 2 
      obj.somemethod2(); 
     case 3 
      obj.somemethod3(); 
     end 
    end 
    function obj = somemethod1(obj) 
     fprintf('1') 
    end 
    function obj = somemethod2(obj) 
     fprintf('2') 
    end 
    function obj = somemethod3(obj) 
     fprintf('3') 
    end 
    end 
end 

test.somemethod()が呼び出されるたびにswitchオペレータが使用されます。私はとして(すなわちメソッド・ハンドラを変更する)クラスのコンストラクタで初期化時に一度だけswitchを使用することができ、次のとおりです。

classdef test < handle 
    properties 
    number 
    somemethod %<-- 
    end 
    methods 
    % function obj = somemethod(obj,number) % my mistake: I meant the constructor 
    function obj = test(number) 
     obj.number = number; 
     switch number 
     case 1 
      obj.somemethod = @(obj) obj.somemethod1(obj); 
     case 2 
      obj.somemethod = @(obj) obj.somemethod2(obj); 
     case 3 
      obj.somemethod = @(obj) obj.somemethod3(obj); 
     end 
    end 
    function obj = somemethod1(obj) 
     fprintf('1') 
    end 
    function obj = somemethod2(obj) 
     fprintf('2') 
    end 
    function obj = somemethod3(obj) 
     fprintf('3') 
    end 
    end 
end 

testクラスのこの第二の実装は動作しません。 S = test(2); S.somemethod()の場合、エラーがあります。 test> @(obj)obj.somemethod2(obj)(行...)を使用しているエラー 入力引数が不十分です。 どうしたの?

答えて

2

まず、のメソッドとしてsomemethodを使用することはできません。メソッドを取り除いて、コンストラクタ内のプロパティに関数ハンドルを割り当てることができます。

function self = test(number) 
    self.number = number; 
    switch self.number 
     case 1 
      self.somemethod = @(obj)somemethod1(obj) 
    %.... 
    end 
end 

はまた、あなたの現在の無名関数は、あなたは、メソッドにオブジェクトのコピーを渡されました:最初の入力

  • obj.method(obj)は、2番目のコピーを渡すよう

    1. obj.methodは、暗黙的にobjを渡します第2入力としてobj

    オブジェクトハンドルを次のようなものに更新し、メソッドにobjの単一コピーを渡します。あなたのクラスを使用しているとき、それはプロパティとメソッドにそれを同じ名前についてプロパティではなく、「本当の」方法

    S = test() 
    S.somemethod() 
    
  • +0

    だから

    obj.somemethod = @obj.somemethod3 

    また、あなたは、ドット表記を使用してsomemethodを実行する必要があります私のtypemistake(私はコンストラクタの初期化を意味した)です。しかし、 'S =テスト(2)。 S.sememethod() 'はエラーを生成します: "テストを使用しているエラー> @(obj)obj.somemethod2(obj)入力引数が不十分です。" –

    +0

    @AlexanderKorovin申し訳ありませんが、私はそれを間違えました。今働いているはずです – Suever

    +0

    ありがとう!残念ながら、この実装( 'obj.somemethod = @ obj.somemethod3')は' switch'を使用した場合より約2倍遅いことがわかりました! –

    関連する問題