% This program analyzes convergence of a particular Fourier series

% Function:
% f(x) = 1-2*|x-0.5| on [0,1]
% Fourier coefficients
% F[2n] = 0 , F[2n+1] = -2/[pi^2 (2n+1)^2] , F[0]=0.5

% Construct finite sums
N = 20;
x = [0:0.01:1]; % row vector
f = 1-2*abs(x-0.5);
PartialSum = zeros(N+1,length(x));
for k=0:N
    if k == 0
        PartialSum(k+1,:) = 0.5*ones(1,length(x));
    elseif mod(k,2) == 0
        % Don't do anything: F[2p ] =0
        PartialSum(k+1,:)=PartialSum(k,:);
    else
        Fk = -2/(pi*pi*k*k);
        Fminusk = -2/(pi*pi*(-k)*(-k));
        PartialSum(k+1,:) = PartialSum(k,:) + Fk*exp(2*pi*i*k*x) + Fminusk * exp(-2*pi*i*k*x);
    end
end


% Plot results
figure(1)
plot(x,real(PartialSum(N+1,:)),'r',x,f,'g')
legend('PartialSum','f')
title(sprintf('N = %d',N))

figure(2)
plot(x,imag(PartialSum(N+1,:)))
title(sprintf('Imaginary Part for N = %d',N))

figure(3)
for k = 0:N
    plot(x,real(PartialSum(k+1,:)))
    hold on
end
