MATLAB: Getting wrong results with fft using length of 2^nextpow2

fftfrequencyspectrum

If i am doing the ftt with the length of 2^nextpow2(L) according to the MATLAB help ( http://de.mathworks.com/help/matlab/ref/fft.html ) and this results in errors in the amplitude of the single-sided spectrum. For example:
Fs = 1e5;
t = (0:1/Fs:0.5);
X = 20*sin(2*pi*300*t);
L = length(t);
% fft code copied from official matlab example code
n = 2^nextpow2(L);
Y = fft(X,n);
f = Fs*(0:(n/2))/n;
P2 = abs(Y/n);
P1 = P2(1:n/2+1);
P1(2:end-1) = 2*P1(2:end-1);
semilogx(f,P1)
In other MATLAB answers ( https://de.mathworks.com/matlabcentral/answers/116357-getting-wrong-results-with-fft#answer_124573 ) there is the amplitude calculation done with the length of the time vector t:
P2 = abs(Y/L);
This seems to be more correct as the amplitude should be 20 in the spectrum. There is another explanation in https://de.mathworks.com/matlabcentral/answers/29696-fft-am-i-doing-anything-wrong#answer_38082 , but is however scaled by sampling frequency Fs and it returns still the wrong amplitude. Is it possible, that there is a mistake in the MATLAB help? How should a fft with the length 2^nextpow2(L) (for performance reasons) be done to obtain correct amplitudes? Thanks a lot in advance!

Best Answer

To get the correct amplitudes, you have to divide the Fourier transform by the length of the original signal, not the zero-padded signal. To plot the one-sided Fourier transform, you then have to multiply the absolute value by 2 in order to correct for the one-sided transform having half the signal energy of the two-sided transform.
The documentation version I always recommend is from the R2015a version: fft (link).