필터 지우기
필터 지우기

Unexpected behavior of anonymous function

조회 수: 1 (최근 30일)
Khaled Hamed
Khaled Hamed 2013년 1월 24일
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)
k =
@(varargin)cellfun(@(x)x^2,varargin)
>> k(:)
ans =
@(varargin)cellfun(@(x)x^2,varargin)
>> k(1)
ans =
1
>> k(1,:)
ans =
@(varargin)cellfun(@(x)x^2,varargin)
>> k(1,2)
ans =
1 4
>> k(1,1,:)
ans =
1 1 3364
>> k(1,2,:)
ans =
1 4 3364
  댓글 수: 3
Sean de Wolski
Sean de Wolski 2013년 1월 24일
@Cedric, apparently. I'm just puzzled by the discrepancy between the second and third dimension.
Cedric
Cedric 2013년 1월 24일
편집: Cedric 2013년 1월 24일
@Sean: yes, it is as if when S.subs is larger than 2, subs are not treated the same way.. and it is not the position of ':' in the subs that matters:
>> k(:,1,2)
ans = 3364 1 4

댓글을 달려면 로그인하십시오.

채택된 답변

Steve Eddins
Steve Eddins 2013년 1월 24일
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!
>> sin(:)
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.
  댓글 수: 1
Khaled Hamed
Khaled Hamed 2013년 1월 24일
I do agree. It just seemed logical that k(:), k(1,:), k(1,1,:), and k(1,2,:) would be interpreted as indexing (the first three would work for a scalar, while the fourth would error).

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2013년 1월 24일
Please contact us and reference this thread.
That certainly looks like obscure behavior.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by