How does MATLAB resolve a function handle with multiple levels of indexing
3 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Matt J
on 23 Dec 2024
Edited: Matt J
on 23 Dec 2024
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.
More Answers (0)
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!