% fft_demo2
% Compare Fourier series for h11=step function  
%                        and h12=sawtooth wave
n=256;
x1=linspace(0,2*pi,n+1)';
x=x1(1:n);
% step function h1
h11=ones(n+1,1);
h11(n/2+1:n+1)=-ones(n/2+1,1);
h11(n/2+1)=0;
figure(1)
plot(x1,h11,'o',[0 pi],[1 1],[pi,2*pi],[-1 -1]);
axis([0 7 -2 2]);
hold on;
h1=h11(1:n);
c1=fft(h1);  % n x Fourier coefficients
x4=linspace(0,2*pi,4*n+1);
% pad Fourier coefficients with zeros
c41=zeros(4*n,1);
c41(1:n/2)=c1(1:n/2);
c41(3*n+n/2+1:4*n)=c1(n/2+1:n);
h41=4*ifft(c41);  % use ifft to evaluate Fourier series at 4n pts
h411=[h41;h41(1)];
plot(x4,h411);
% sawtooth wave h2
figure(2)
h12(1:n/2+1)=x1(1:n/2+1);
h12(n/2+2:n+1)=2*pi-x1(n/2+2:n+1);
plot(x1,h12,'o',[0 pi],[0 pi],[pi,2*pi],[pi 0]);
axis([0 7 0 7]);
hold on;
h2=h12(1:n);
c2=fft(h2);  % Fourier coefficients
x4=linspace(0,2*pi,4*n+1);
c42=zeros(4*n,1);
c42(1:n/2)=c2(1:n/2);
c42(3*n+n/2+1:4*n)=c2(n/2+1:n);
h42=4*ifft(c42); % use ifft to evaluate Fourier series at 4n pts
h421=[h42;h42(1)];
plot(x4,h421);
figure(3)
%hold off;
loglog(1:n/2,abs(c1(1:n/2)/n),'.', 1:n/2,abs(c2(1:n/2)/n),'o')
legend('step','saw')  
axis([1 n/2 10^(-5) 1]);

