MATLAB: Amplitude Error in amplitude Spectrum of FFT

.amp

Hello
I'm currently working on FFT on cosine and sine function. I want to get the FFT graph to be plotted. The graph of the FFT looks fine except that the value of the amplitude were a bit off.
The amplitude was suppose to be '1', however, at different frequency, the amplitude will change from 0.8 to 1.5.
The code looks like this: Fs=1000 t=0:1/Fs:1;
NFFT = 2^nextpow2(length(x)); y = fft(x,NFFT)/length(x); y = y(1:NFFT/2+1); my = 2*abs(y); f = Fs/2*linspace(0,1,NFFT/2+1);
plot(handles.freqdomain,f,my) xlabel('Frequency(Hz)') grid on
Any help is appreciated. Thanks in advance.

Best Answer

I suspect that your frequency of interest is simply not falling on a DFT bin directly. Why do you think you need to use a power of two for the DFT?
For example, if I have data sampled at 1 kHz and I have 1000 points, then frequency increment in DFT bins is 1 Hz (the bins are 1 Hz apart) so a frequency of 100 Hz for example will fall directly on a bin.
Fs = 1000;
t = 0:1/Fs:1-1/Fs;
x = 1.5*cos(2*pi*100*t);
xdft = fft(x);
freq = 0:Fs/length(x):Fs/2;
xdft = xdft(1:length(x)/2+1)./length(x);
xdft(2:end) = 2*xdft(2:end);
plot(freq,abs(xdft))
See that the magnitude is estimated exactly. Now watch what happens when I pad to 1024:
xdft = fft(x,1024);
freq = 0:Fs/length(xdft):Fs/2;
xdft = xdft(1:length(xdft)/2+1)./length(x);
xdft(2:end) = 2*xdft(2:end);
plot(freq,abs(xdft))
by padding to 1024, I have now made the frequency of interest fall between DFT bins and that makes my amplitude estimate inaccurate.
in the Signal Processing Toolbox documentation