Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
780 views
in Technique[技术] by (71.8m points)

oop - How to get the handle of a method in an Object (class inst) within MATLAB

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!
', 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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...