I have a function for cached evaluation. As one of the arguments, it takes a function handle. Under some circumstances, the function handle is unaccessible, and I don't quite understand why. The example below shows what got me stumped:
>> A.a = @plus; feval(@A.a, 1, 1)
ans =
2
>> clear A
>> A.a.a = @plus; feval(@A.a.a, 1, 1)
Error using feval
Undefined function 'A.a.a' for input arguments of type 'double'.
So, if I have a function handle stored as a structure member, I can pass it along fine if it's one level deep, but not if it's two levels deep. In my real use case, I have a structure D
that holds many (117) instances of various classes, so I actually have stct.obj.meth
, where stct
is a structure, obj
is a class instance/object, and meth
is a method. Passing @stct.obj.meth
fails, but if I assign A = stct.obj
, then passing @A.meth
succeeds.
Under what conditions can I pass a function handle as an argument, so that it's still accessible down the stack?
Edit: Although in the use case above, I could simply remove the @
because @plus
is already a function handle. However, consider the situation here:
>> type cltest.m
classdef cltest < handle
methods
function C = mymeth(self, a, b)
C = a + b;
end
end
end
>> A.a = cltest();
>> feval(@A.a.mymeth, 1, 1)
Error using feval
Undefined function 'A.a.mymeth' for input arguments of type 'double'.
>> b = A.a;
>> feval(@b.mymeth, 1, 1)
ans =
2
In this case, I need the @
before A.a.mymeth
...
@A.a.mymeth
does not produce a valid function handle, but it is worth noting that in your first example the extra@
is not needed. You could useA.a = @plus; feval(A.a,1,1);
becauseA.a
is already a function pointer. – Fariss