% Demo for CT and DT FS, Sep 2005, mh
%
% CT, see Example 3.5 on p. 193
disp('Continuous-time Fourier series')
figure(1);
t=-2:0.01:2;
T=2;
s=floor(t+1/2);
x=1/2*(1+rectwin(length(t))'.*(-1).^s); % create even periodic signal with T_1=1/2
plot(t,x);
axis([min(t) max(t) -0.2 1.2])
pause
f=0*t;
for k=0:20
    K=k
    if k==0 
        a_k=1/2  % coefficient a_0
        a=a_k/2;
    else
        a=sin(k*pi/2)./(k*pi); % coefficients a_k, k>0
        if abs(a)<1e-10 a=0; end;
        a_k=a
    end
    f=f+a*2*cos(k*(2*pi/T)*t); % combine a_k and a_(-k) to a cosine
    plot(t,x,t,f,'r');
    axis([min(t) max(t) -0.2 1.2])
    set(gca,'FontSize',16);
    s=sprintf('%3d',2*k+1);
    title(['CT Fourier Series with ',s,' coefficients'],'FontSize',16)
    pause
end
% DT, see Example 3.12 on p. 218
disp(' ');
disp('Discrete-time Fourier series')
figure(2)
n=-22:22; % DT time axis
N=15;
x=mod(n+3,N)<7; % N_1=3
stem(n,x)
axis([min(n) max(n) -0.2 1.2])
pause;
f=0;
for k=0:7
    K=k
    if k==0
        a_k=(2*3+1)/N
        a=a_k/2;
    else
        a=1/N*sin(2*pi*k*(3+1/2)/N)/sin(pi*k/N);
        if abs(a)<1e-10 a=0; end;
        a_k=a
    end
    f=f+a*2*cos(k*2*pi/N*n);
    stem(n,x)
    axis([min(n) max(n) -0.2 1.2])
    hold on
    plot(n,f,'or')
    hold off
    set(gca,'FontSize',16);
    s=sprintf('%3d',2*k+1);
    title(['DT Fourier Series with ',s,' coefficients'],'FontSize',16)
    pause
end
disp('The DT FS is exact!')

