How to get a method handle in an object (inst class) in MATLAB

I'm trying to grab a method handle from an object in MATLAB, but something in the form of str2func ('obj.MethodName') does not work

+6
methods oop class matlab
source share
4 answers

The answer is to get a function descriptor like @Pablo .

Please note that your class must be obtained from the handle class in order for it to work correctly (so that the object is passed by reference).

Consider the following example:

hello.m

 classdef hello < handle properties name = ''; end methods function this = hello() this.name = 'world'; end function say(this) fprintf('Hello %s!\n', this.name); end end end 

Now we get the handle to the member function and use it:

 obj = hello(); %# create object f = @obj.say; %# get handle to function obj.name = 'there'; %# change object state obj.say() f() 

Exit:

 Hello there! Hello there! 

However, if we define it as a Value Class (change the first line to classdef hello ), the result will be different:

 Hello there! Hello world! 
+6
source share

You can also write

 fstr = 'say'; obj.(fstr)(); 

This has the advantage of not requiring the descriptor class to work if the object (obj) is modified.

+6
source share

Use @ . The following code works for me:

 f = @obj.MethodName 
+5
source share

No other answer mimics str2func('obj.MethodName') . In fact, this is not so, not really. But you can define a helper function as follows:

 function handle = method_handle(obj, mstr) handle = @(varargin) obj.(mstr)(varargin{:}); end 

Then method_handle(obj, 'MethodName') returns a handle to obj.MethodName . Unfortunately, you cannot pass the variable name obj as a string - eval("obj") will not be defined in the scope of the function.

0
source share

All Articles