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: ''

采纳的回答

Matt J
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
f = function_handle with value:
@(varargin)obj.func(varargin{:})
s.obj=obj;
f=@s.obj.func
f = function_handle with value:
@s.obj.func
I think it's undocumented.
  1 个评论
Jim Hokanson
Jim Hokanson 2024-12-24,3:10
Yeah, my impression is that this is undocumented behavior. I'm not a function handle expert though and thought maybe this was obvious to someone else.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by