MATLAB: How to pass a method as a function handle

functionshandlesMATLABoop

Ok, so I have an object as a property of a class. This object has methods. I need to use an object's method as a handle, like follows:
classdef MyClass
properties
my_obj_with_methods
end
methods
function r = foo(obj, func, a, b)
r = func(a, b);
end
function r = bar(obj)
r = obj.foo(@obj.my_obj_with_methods.my_method, 1, 2);
end
function r = foobar(obj)
r = obj.foo(@obj.my_obj_with_methods.my_other_method, 1, 2);
end
end
end
When I try to do this, I get:
"Undefined function or variable 'obj.my_obj_with_methods.my_method"
1 – I know I can solve this with an `if/else`, but I thought "hey, Matlab is a functional language, I could use those great functional features!"
2 – I'm not complicating things, I have good reason to want to do this
Thanks!

Best Answer

I think the issue is that to use the @ construction, the thing you're applying it to needs to be named function in scope. There is no function "called" obj.my_obj_with_methods.my_method, that construction accesses the method another way.
so you can use the following piece of delight which does work, but is as ugly as sin:
classdef MyClass
properties
my_obj_with_methods
end
methods
function r = foo(obj, func, a, b)
r = func(a, b);
end
function r = bar(obj)
r = obj.foo(@(varargin) obj.my_obj_with_methods.my_method(varargin{:}), 1, 2);
end
function r = foobar(obj)
r = obj.foo(@(varargin) obj.my_obj_with_methods.my_other_method(varargin{:}), 1, 2);
end
end
end
Or ... use python (**ducks**)
Related Question