So today i noticed something i think is weird.
Say i define an anonyomous function.
f = @(x) ... Now if i input f(end) it will evaluate the function at f(1).
Is this a bug or is there a reason for this behaviour?
Regards Michael

 Akzeptierte Antwort

James Tursa
James Tursa am 23 Mär. 2018
Bearbeitet: James Tursa am 23 Mär. 2018

0 Stimmen

Weird, but it does match the doc for end:
"... end = (size(x,k)) when used as part of the kth index ..."
E.g.,
>> f = @(x)x+5
f =
@(x)x+5
>> size(f,1)
ans =
1
>> f(1)
ans =
6
>> f(end)
ans =
6
f(end) appears as an indexing expression to MATLAB. Since the size of the f variable is 1x1, it uses 1 for end.

3 Kommentare

Stephen23
Stephen23 am 23 Mär. 2018
Bearbeitet: Stephen23 am 23 Mär. 2018
It is weird: why does it get interpreted as an indexing operation in the first place?
If a function handle has size 1x1, then why can't we create non-scalar function handles?
James Tursa
James Tursa am 23 Mär. 2018
Bearbeitet: James Tursa am 23 Mär. 2018
Seems the parser processes the 'end' first and effectively does a replacement, without regard to whether the variable in question is a function handle or not. It does have a weird effect, however, in that the index itself gets magically turned into an argument for the function handle. E.g., using the same example:
>> f = @(x)x+5
f =
@(x)x+5
>> f(end-5)
ans =
1
>> f(end+10)
ans =
16
So IMO this behavior should be disallowed and should throw an error. But that may mean the parser would have to be smarter and examine the variable class before doing the replacement. Maybe a bug report or enhancement request to TMW is in order.
Michael
Michael am 23 Mär. 2018
Sent a message to TMW. Thanks for the explanations of the phenomenon.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu MATLAB finden Sie in Hilfe-Center und File Exchange

Produkte

Gefragt:

am 23 Mär. 2018

Kommentiert:

am 23 Mär. 2018

Community Treasure Hunt

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

Start Hunting!

Translated by