# Why cant DFT be implemented this way?

I am trying to implement the discrete Fourier transform.Here is my code in MATLAB:

sym k
n = 1:4;
disp(n);
y = n-2>=0;
z = n-4>=0;
x = y-z;

X(k) = sum(x.*exp(-1i*2*pi*k.*n/4));

l = 1:4;
subplot(1,2,1);
stem(l,abs(X(l)));
subplot(1,2,2);
stem(l,angle(X(l)));


I get these results for magnitude and phase: However when I try to put the values [0,1,1,0] in this DFT calculator I don't get the same results. Where is the error in my code?

You're missing the 0 frequency. Recall the definition of the DFT: $$X[k] = \sum_{n =0}^{N-1}x[n]e^{-j2\pi \frac{k}{N}n}\quad\quad k = 0, 1, \dots, N-1$$

n = 1:4;
y = n-2>=0;
z = n-4>=0;
x = y-z;

for k = 1:4
X(k) = sum(x .* exp(-1j*2*pi*(k-1).*(n-1)/4));
end


gives the correct result.

• But it doesnt let me do it it hits a error at "X(k) = sum(x .* exp(-1j*2*pi*(k-1).*(n-1)/4));" Jan 23 at 22:37
• It has to do with the fact that it treats k as symbolic variable so k-1 isnt correct. Jan 23 at 22:41
• Why are you using sym k, just use the code I provided, that's what the DFT is.
– Jdip
Jan 23 at 22:45
• It still doesnt get compiled. Jan 23 at 22:48
• Yes it does maybe if I restart the MATLAB the issue gets solved. Jan 23 at 22:51