% ---------------------------------
% fft_test.m
% Tests Fourier transforms
% Original m-file by J. Merikoski
% ---------------------------------
clear all; close all;
N=128; x=linspace(0,(N-1)/N,N);
% Sample functions:
%y = cos(2*pi*x);
y(1:N/4)=-1; y(1+N/4:N/2)=+1; y(1+N/2:3*N/4)=-1; y(1+3*N/4:N)=+1;
%y(1:N/2) = 0; y(1+N/2:N) = 1; 
 
% plot original function
subplot(2,3,1);
plot(x,y,'b.'); 
title('Original function'); xlabel('x'); ylabel('f(x)');
Fy=fft(y,N);

% Fourier coefficients in exp basis 
subplot(2,3,2);
plot(real(Fy),'bx'); hold on;
plot(imag(Fy),'mo');
legend('real','imag');
title('Fourier coeffients');xlabel('k index'); ylabel('f(k)');

% Fourier coefficients in {sin,cos} basis 
subplot(2,3,3);
sinK=-(2/N)*imag(Fy(1:N/2)); sinK(1)=0;
cosK=+(2/N)*real(Fy(1:N/2)); cosK(1)=cosK(1)/2;
plot(sinK,'bx'); hold on;
plot(cosK,'mo');
legend('sin','cos');
title('Fourier coefficients in \{sin,cos\} basis');
xlabel('k index'); ylabel('f(k)')

% inverse transform
FFy=ifft(Fy,N);
subplot(2,3,4);
plot(x,y,'b.'); hold on;
plot(x,real(FFy),'m-');
%legend('y=f(x)','F^{-1}(F(y))');
title('Inverse transform');
xlabel('x'); ylabel('f(x)'); 



% inverse transform using sin and cos functions
subplot(2,3,5);
kx=10;
for kmax = 1:kx
    ya=0;
    for k=1:kmax,
        ya=ya+sinK(k)*sin((k-1)*2*pi*x)+cosK(k)*cos((k-1)*2*pi*x);
    end
    
end
plot(x,y,'b.');   hold on;
plot(x,real(ya),'m-');  
xlabel('x'); ylabel('f(x)'); 
title(['Truncated Fourier series',10,'1-', int2str(kx),' terms']);

