% convolution demonstration

x = 0:99;
f = [ 0.6*ones(1,20), 0.5 * ones(1,20), ones(1,20), ...
      ((19:-1:0)/40+0.5), ((19:-1:0)/80+0.25) ];

% sample averaging filter - smooths f
g1 = ones(1,11)/11;
h1 = conv(f, g1);
x1 = -5:104;
subplot(1,1,1);
plot( x, f, x1, h1 );

% try same filter with FFTs
F = fft(f);
g1 = [ones(1,6),zeros(1,89), ones(1,5)]/11;
G1 = fft( g1 );
H1 = F .* G1;
h1_ = ifft( H1 );
subplot(2,1,1);
plot( x, f, x, real(h1_), x1, h1 );
subplot(2,1,2);
%plot( x, abs(F), x, abs(G1), x, abs(H1) );
plot( x, abs(G1));


% sample averaging filter - smooths f - wider window
%g2 = ones(1,21)/21;
%h2 = conv(f, g2);
%x2 = -10:109;
%subplot(1,1,1);
%plot( x, f, x1, h1, x2, h2 );

% repeat with FFTs
%g2 = [ones(1,11),zeros(1,79), ones(1,10)]/21;
%G2 = fft( g2 );
%H2 = F .* G2;
%h2_ = ifft( H2 );
%subplot(2,1,1);
%plot( x, f, x, real(h2_), x2, h2 );
%subplot(2,1,2);
%plot( x, abs(F), x, abs(G1), x, abs(H1) );
%plot( x, abs(G2), x, abs(G1));

% demonstrate application to noise reduction
%fn = f + 0.1 * randn(size(f));
%g1 = ones(1,11)/11;
%g2 = ones(1,21)/21;
%h1 = conv(fn, g1);
%h2 = conv(fn, g2);
%subplot(1,1,1)
%plot(x, f, x, fn, x1, h1, x2, h2 );
