6

I'm trying to grab a method handle from within an object in MATLAB, yet something in the sort of str2func('obj.MethodName') is not working

AlaShiban
  • 215
  • 3
  • 8
  • 1
    I now realize that I might have skipped an important part of the question: My goal is to take a function name through a string (char array), and run it (for autodetection of available functions within a class for instance) - This seems to work generally, but specifically within classes, running feval with ['obj.' functionName], where functionName is some char array, does not resolve. Thanks in advance – AlaShiban Oct 03 '11 at 10:56
  • have you considered using [meta-information](http://www.mathworks.com/help/techdoc/matlab_oop/br4iuh2.html) of classes/objects. I did post an example in a previous question of yours: http://stackoverflow.com/questions/7102828/instantiate-class-from-name-in-matlab/7107012#7107012 – Amro Oct 03 '11 at 15:54

4 Answers4

6

One could also write

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

This has the advantage that it does not require a handle class to work if the object (obj) is modified.

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
skm
  • 329
  • 2
  • 9
6

The answer is to get a function handle as @Pablo has shown.

Note that your class should be derived from the handle class for this 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 a 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()

The output:

Hello there!
Hello there!

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

Hello there!
Hello world!
Community
  • 1
  • 1
Amro
  • 123,847
  • 25
  • 243
  • 454
5

Use @. The following code works for me:

f = @obj.MethodName
Pablo
  • 8,644
  • 2
  • 39
  • 29
1

No other answer mimics str2func('obj.MethodName'). Actually, this one doesn't either, not exactly. But you can define an auxillary function like so:

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 of obj as a string - eval("obj") will be undefined in the function's scope.

llf
  • 610
  • 10
  • 11