% Fourier Cosine Series for the Repeating Ramp, Animation adds a new term per frame.
% David Bloore, August 9, 2011

ccc=input('Case?');

switch ccc;
    case 1
        lb=-pi;
        ub=pi;
        s=10000;
        t=150;
    case 2
        lb=-2*pi;
        ub=2*pi;
        s=10000;
        t=150;
    case 3
        lb=-3*pi;
        ub=3*pi;
        s=10000;
        t=150;
    case 4
        lb=-9*pi;
        ub=9*pi;
        s=30000;
        t=150;
end

x=linspace(lb,ub,s);

y=pi/2-4/pi*cos(x);
n=1;

p=plot(x,y);
legend('Truncated Fourier Series Terms','Location','best');
title('Truncated Fourier Cosine Series for the Repeating Ramp');
xlabel([sprintf('%d',lb) ' \leq x \leq ' sprintf('%d',ub)]);
ylabel('y');
grid on;
set(gcf,'Position',[0 356 1440 900]);

while n<t+1
    n=n+2;
    for cc=1:s;
        y(cc)=y(cc)-4/(pi*n^2)*cos(n*x(cc));
    end
    set(p,'YData',y);
    drawnow
end