Unexpected behavior of anonymous function
2 views (last 30 days)
The anonymous function k below behaves correcltly except for the last two cases k(1,1,:) and k(1,2,:), where it interprets the semicolon as a charcter (':'=58, 58^2=3364), while it should return the handle in the first case and error in the second. Any explanations?
>> k=@(varargin) cellfun(@(x) x^2,varargin)
1 1 3364
1 4 3364
Steve Eddins on 24 Jan 2013
First, I would like to point out that k(1,1,:) is a valid expression for a subscripting operation on a variable called k, but it is not a valid expression for a call to a function called k.
In other words, you can't pass a "naked" colon as a function argument!
Undefined variable sin.
So k(:), k(1,:), k(1,1,:), and k(1,2,:) are all invalid ways to call a function (or a function handle).
The fact that MATLAB isn't just giving a quick error on these expressions is an artifact of the way function handle evaluation syntax using parentheses has been implemented. It's been implemented by overloading the parentheses syntax using subsref. By the time the subsref overload sees things, the "naked" colon has been converted to a character. Like everything else inside the parentheses, this character then gets treated as a function argument.