Call class A method from class B using function handle?

Please see below example:
classdef MainClass
properties
Prop1
end
methods
function obj = MainClass()
obj.Prop1 = ClassB;
obj.Prop1.SetMethod(@MyMethod);
end
function MyMethod(obj)
disp('MainClass MyMethod called')
end
end
end
classdef ClassB < handle
properties
UpdateMethod
end
methods
function SetMethod(obj,newMethod)
obj.UpdateMethod = newMethod;
end
function CallUpdateMethod(obj)
obj.UpdateMethod();
end
end
end
>> x = MainClass;
>> x.Prop1.CallUpdateMethod;
Unrecognized function or variable 'MyMethod'.
Error in ClassB/CallUpdateMethod (line 10)
obj.UpdateMethod();
I'd like to call MainClass MyMethod from ClassB however am misunderstanding how this should be done. Any help would be appreciated. Thanks

 採用された回答

Matt J
Matt J 2022 年 12 月 11 日

0 投票

function obj = MainClass()
obj.Prop1 = ClassB;
obj.Prop1.SetMethod(@()obj.MyMethod);
end

3 件のコメント

SoderlingPotro
SoderlingPotro 2022 年 12 月 12 日
編集済み: SoderlingPotro 2022 年 12 月 12 日
Thanks Matt, I couldn't figure this out from the docs. I'm still having an issue. Say MyMethod takes in an argument e.g. function MyMethod(obj, arg1). How should the function handle signature be?
Matt J
Matt J 2022 年 12 月 12 日
obj.Prop1.SetMethod(@(arg1)obj.MyMethod(arg1))
SoderlingPotro
SoderlingPotro 2022 年 12 月 12 日
編集済み: SoderlingPotro 2022 年 12 月 12 日
Got it, thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLinear Algebra についてさらに検索

製品

リリース

R2021a

質問済み:

2022 年 12 月 11 日

編集済み:

2022 年 12 月 12 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by