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)(行...)を使用しているエラー 入力引数が不十分です。 どうしたの?
だから
また、あなたは、ドット表記を使用して
somemethod
を実行する必要があります私のtypemistake(私はコンストラクタの初期化を意味した)です。しかし、 'S =テスト(2)。 S.sememethod() 'はエラーを生成します: "テストを使用しているエラー> @(obj)obj.somemethod2(obj)入力引数が不十分です。" –@AlexanderKorovin申し訳ありませんが、私はそれを間違えました。今働いているはずです – Suever
ありがとう!残念ながら、この実装( 'obj.somemethod = @ obj.somemethod3')は' switch'を使用した場合より約2倍遅いことがわかりました! –