MATLAB: The amplitude of fft computing is a little bit different from a known value

amplitudefftfrequencymagnitudeMATLAB

I was trying test this:
n=5000;
ts=5;
t=[0:ts/n:ts];
x1=sin(2*pi*20*t);
x2=2*sin(2*pi*60*t);
x3=20*sin(2*pi*200*t);
x4=15*sin(2*pi*350*t);
x=x1+x2+x3+x4;
N=length(x);
k=[0:N-1];
T=N/Fs;
freq=k/T;
cutoff=ceil(N/2);
X=fftn(x)/(N/2);
X=abs(X);
stem(freq(1:cutoff),X(1:cutoff))
The magnitudes got different results to 1 (x1); 2 (x2); 20 (x3) and 15 (x4). And more…if "n" has more or less points for computing the fft, the frequencies (20, 60, 200, 350) also change. Why? Can someone help me? Thanks a lot.

Best Answer

You have to realize that the frequency spacing between DFT elements depends on the length of the DFT and the sampling frequency. If your frequencies do not fall directly on a DFT bin (the spacing is Fs/N where Fs is the sampling frequency and N the length of the DFT) then the energy in a particular component will be mapped to a slightly different frequency.
Here is your example the way you think it should look:
n=5000; ts=5; t=[0:ts/n:ts-ts/n];
x1=sin(2*pi*20*t); x2=2*sin(2*pi*60*t); x3=20*sin(2*pi*200*t);
x4=15*sin(2*pi*350*t); x=x1+x2+x3+x4;
xdft = fft(x);
xdft = xdft(1:length(x)/2+1);
xdft(2:end-1) = 2*xdft(2:end-1);
xdft = xdft./length(x);
df = 1000/length(x);
freq = 0:df:500;
plot(freq,abs(xdft));
xlabel('Hz'); ylabel('Magnitude');
grid on;
You may want to review this: