I don't know where you got that formula in the image from, but for an N
-point fourier transform of a discrete signal, you only need to sum over k
from 0
to N-1
to get an exact reconstruction. N
orthogonal basis functions can reconstruct any N
-dimensional signal. You might be confusing the DTFT with the DFT (you want the second of these).
I also don't understand the formulas you used for the ak
coefficients. You calculate them with sin
and then sum them up with complex exponentials rather than sine waves.
If you want to do a discrete fourier transform (DFT) with a complex exponentials, the code should look similar to mine below. You get the ck
coefficients from the inner product of the time signal x
and the complex basis functions.
clear; clc;
N = 20; %// number of points
x = [zeros(1,N/4),ones(1,N/2),zeros(1,N/4)]; %//time signal data
n = 0:N-1;
ck = zeros(1,N);
for k = 0:N-1 %//cacluate coefficients
ck(k+1) = sum(x.*exp(-1i*2*pi*k*n/N));
end
xN = zeros(1,N);
for k = 0:N-1 %// add partial frequencies
xN = xN + ck(k+1)*exp(1i*2*pi*k*n/N)/N;
end
plot(n,xN)

If you want to do an ordinary fourier series using real sinusoids, your code should look like this:
clear; clc;
N = 20; %// number of points
T = 1; %// fundamental frequency
omega = 2*pi/T; %// angular frequency
t = linspace(-0.5,0.5,N); %// time points
x = [zeros(1,N/4),ones(1,N/2),zeros(1,N/4)]; %// time signal data
a0 = sum(x)/N; ak = zeros(1,N); bk = zeros(1,N);
for k = 1:N-1 %// calculate coefficients
ak(k) = sum(x.*cos(omega*k*t))/N;
bk(k) = sum(x.*sin(omega*k*t))/N;
end
xN = a0*cos(omega*0*t); %// add DC offset
for k = 1:N-1 %// add partial frequencies
xN = xN + ak(k)*cos(omega*k*t) + bk(k)*sin(omega*k*t);
end
plot(t,xN)