calculating DFT of time signal in MATLAB

86 Views Asked by At

This code computes the DFT from time domain. Can anybody see the code below and help me to get the right answer? my problem is: when I change N value, for example, to 4, 5, 10 ,or other values. X(1) changes with that. but I think X(1) must be the same for every value of N. just like the shape below: the N value changes but the vertical value is the same. I appreciate if you help me. Thank you.

enter image description here

clear; clc;
% %%  Analytical
N=4;
k=0:N-1;
X=zeros(N,1);
t=k/N;
x=(5+2*cos(2*pi*t-pi/2)+3*cos(4*pi*t))
%x=abs((1-(0.012.*(pi.*52.*(t-0.3721)).^2)).*exp(-(pi.*52.*(t-0.3721).^2)))
abs(sum(x))

for k=0:N-1
    for n=0:N-1
        X(k+1)=X(k+1)+x(n+1).*exp(-1i.*2.*pi.*(n).*(k)/N);
    end
end

k1=[0:N-1];
stem(k1,abs(X))
% xlim([0 1])
% ylim([-1 1])
xlabel('Frequency');
ylabel('|X(k)|');
title('Frequency domain - Magnitude response')
1

There are 1 best solutions below

0
Eric Backus On

Your definition of DFT (which is probably the most common definition) does not have the property that X(1) remains constant with N. Instead, it is X(1)/N which will remain constant. To use this DFT to get the magnitudes of the input at various frequencies, you'll need to divide the DFT output by N.

To verify this, you can call Matlab's fft function and compare with your results. You should get the same answer from Matlab's fft. Note that Matlab's fft documentation says:

The resulting FFT amplitude is A*n/2, where A is the original amplitude and n is the number of FFT points.