Why it is not possible to do array indexing directly after function that returns array?

11 views (last 30 days)
Maybe it is a stupid question but I don't understand why it is not possible to do array indexing directly after function in my case fft(signal).
My code looks like this:
fs = 48000;
N = fs;
n = 0 : N-1;
sin440 = sin((2*pi/N)*440*n);
Y = fft(sin440);
frequencySpectrum = abs(Y(1:fs/2));
This works just fine but why is not possible in Matlab to replace last two rows with just one; like this:
frequencySpectrum1 = abs(fft(sin440)(1:fs/2))
This row gives this error:

Accepted Answer

Walter Roberson
Walter Roberson on 3 Apr 2021
"because".
I am not sure if anyone remembers the original reason. In part, it was because the parser contained a lot of custom code and it was difficult to extend. However I can tell that Mathworks must have redone the parser a few years ago, so perhaps we will see further changes.
Part of the reason is that functions are permitted to be called with no parameters, so if indexing the result of a function is permitted, the syntax F(x) becomes ambiguous as to whether it means "call F with parameter x" or "call F with no parameters and index the result at x"
But these reasons are speculation.

More Answers (2)

Bruno Luong
Bruno Luong on 3 Apr 2021
Edited: Bruno Luong on 3 Apr 2021
There might be some syntax confusion that leads TMW not to do that. The issue is that the indexing and function argument both use parenthesis "(" ")".
For the moment
z = peaks
return arrays 49 x 49
z = peak(10)
returns now output 10 x 10. That is OK.
But let us suppose the proposed casecade indexing parenthesis, then given the expression
z = peaks(10)
should the parser decides that is equivalent to
z = peak
z = z(10)
or just 10 is the argument of peak ?

JK
JK on 5 Apr 2021
Thank you very much to both of you. I understand now.

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!