Is there an inconsistency when creating a function handle to an object's method in MATLAB 7.9 (R2009b)?

2 views (last 30 days)
There is a difference in the behavior of function handles for methods of User Defined Objects.
Say I have the following class definition:
classdef MyClass < handle
properties
myprop;
end
methods
function obj = MyClass()
obj.myprop = rand();
end
function mymethod(obj)
disp(['in mycallback : property value: ' num2str(obj.myprop)]);
end
end
end
a = myClass(); % create an instance
f = @a.mymethod % Creating a function handle: this works
a(2) = MyClass(); % Now Create an object array:
% Trying to define a function handle in the following ways works fine:
f = @a.mymethod % this works CASE1
f = @() a(2).mymethod % this works CASE2
% However this fails with an "Unbalanced or unexpected parenthesis or bracket." error
f = @a(2).mymethod() % this errors CASE3
f = @a.mymethod() % this does not work CASE4

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 19 Jan 2010
This behavior is expected. However, what you are seeing is actually due to how the function handles are defined. The parenthesis in the function handle definition are causing this error. MATLAB accepts parenthesis in the function handle definition only if @ is followed by an empty set of brackets( @() ... ).
Case 1: This uses the syntax for forming a handle to a method of an object.
- It consists of two parts - a variable name and a method name.
- There is no indexing or expression so there need not be any parentheses.
Case 2: This is an anonymous function which also consists of two parts
- an argument list and an expression.
Case 3: This is neither valid syntax for a method on an object nor valid syntax for an anonymous function handle. Case 1 uses a convenient syntax for a common situation - calling a method on a particular object.
Anything more complicated needs to use the more general anonymous function syntax.

More Answers (0)

Products


Release

R2009b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!