It would be more efficient to use a vector form of the DFT for the coding in matlab. As an example, see below. Note that this method is only best for shorter sequences ,x(n), if you have a larger value for N, then another method would be preferred.
clear variables
close all
xn = [0 2 4 6 8];
N = length(xn);
n = 0:1:N-1;
k = 0:1:N-1;
WN = exp(-1i*2*pi/N);
nk = n'*k;
WNnk = WN .^ nk;
Xk = xn * WNnk;
disp('The DFT of x(n) is Xk = ');
disp(Xk)
magXk = abs(Xk);
n = 0:1:N-1;
k = 0:1:N-1;
WN = exp(-1i*2*pi/N);
nk = n'*k;
WNnk = WN .^ (-nk);
x_hat = (Xk * WNnk)/N;
disp('and the IDFT of x(n) is x_hat(n) = ');
disp(real(x_hat))
subplot(3,1,1);
stem(k,xn,'linewidth',2);
xlabel('n');
ylabel('x(n)')
title('plot of the sequence x(n)')
grid
subplot(3,1,2);
stem(k,magXk,'linewidth',2,'color','r');
xlabel('k');
ylabel('Xk(k)')
title('DFT, Xk')
grid
subplot(3,1,3);
stem(k,real(x_hat),'linewidth',2,'color','m');
xlabel('n');
ylabel('x(n)')
title('Plot of the inverse DFT, x_{hat}(n) = x(n)')
grid
Best Answer