How does MATLAB resolve a function handle with multiple levels of indexing
33 次查看(过去 30 天)
显示 更早的评论
Imagine that I have classes class1 and class2 and that class2 has a property parent that points to an instance of class1. Class1 has a function called myFunction. Both classes are handle classes. If I set a callback on a uitable in an old style figure (not sure if that is relevant), I get different behavior between the following and I'm curious why.
Approach 1 (in class2) - this doesn't work
h_table.Callback = @obj.parent.myFunction;
Approach 2 - this works
p = obj.parent;
h_table.Callback = @p.myFunction
What's going on here?
I think this works as well although I haven't tested it
Approach 3 - works? (haven't tested)
h_table.Callback = @(a,b)obj.parent.myFunction(a,b);
Why does Approach 1 not work?
I'll note that if you look at the function handle using:
fh = @obj.parent.myFunction; % for fh = @p.myFunction
s = functions(fh)
The resulting structure and info is very different.
For 1 I see: (roughly, modified from actual class names but I think this is accurate)
function: 'obj.parent.myFunction'
type: 'classsimple'
file: ''
class: 'b'
For 2 I see: (again, roughly)
function: '@(varargin)p.myFunction(varargin{:})'
type: 'anonymous'
file: 'b.m'
workspace: {[1×1 struct]}
within_file_path: ''
0 个评论
采纳的回答
Matt J
2024-12-23,1:19
编辑:Matt J
2024-12-23,1:26
Well, ultimately I think Approach 3 is the only 'correct' one. It appears that when the indexing is one level deep (as in Approach 2), Matlab assumes you are trying to build an anonymous function and appends a generic parameter list as a convenience. Otherwise, though, it doesn't know what you want, as demonstrated below.
obj=myclass;
f=@obj.func
s.obj=obj;
f=@s.obj.func
I think it's undocumented.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!