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

조회 수: 19 (최근 30일)
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:

채택된 답변

Walter Roberson
Walter Roberson 2021년 4월 3일
"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.

추가 답변 (2개)

Bruno Luong
Bruno Luong 2021년 4월 3일
편집: Bruno Luong 2021년 4월 3일
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 2021년 4월 5일
Thank you very much to both of you. I understand now.

카테고리

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

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by