%% demo of constructing a square wave from sinusoidal components 
%% and the low-passed version (showing the low-pass filter action
%% on each of the components)
clf;
t=1:10000
  y=zeros(1,10000);
for i=1:2:21
   yadd=sin(2*pi*i/1000*t)/i;
   y=y+yadd;
   subplot(2,2,1), hold on; plot(yadd); title('components of square wave')
   subplot(2,2,2),plot(y); title('constructed square wave');
%  [b,a] = butter(3,4*pi/1000,'high');
   [b,a] = butter(3,2*pi/1000,'low');
%  [b,a] = butter(3,[2*pi/1000, 4*pi/1000]);
   fy=filter(b,a,y);
   fyadd=filter(b,a,yadd);
   subplot(2,2,3), hold on; plot(fyadd); title('low pass filtered components')
   subplot(2,2,4), plot(fy); title('low pass filtered reconstructed square wave')
   pause;
end

figure

%% demo of constructing a square wave from sinusoidal components 
%% and the high-passed version (showing the high-pass filter action
%% on each of the components)

clf;
t=1:10000
  y=zeros(1,10000);
for i=1:2:21
   yadd=sin(2*pi*i/1000*t)/i;
   y=y+yadd;
   subplot(2,2,1), hold on; plot(yadd); title('components of square wave')
   subplot(2,2,2),plot(y); title('constructed square wave');
   [b,a] = butter(3,4*pi/1000,'high');
 % [b,a] = butter(3,[2*pi/1000, 4*pi/1000]);
    fy=filter(b,a,y);
   fyadd=filter(b,a,yadd);
   subplot(2,2,3), hold on; plot(fyadd); title('high pass filtered components')
   subplot(2,2,4), plot(fy); title('high pass filtered reconstructed square wave')
   pause;
end

%%% showing the action of a very simple low pass filter discussed in class

alpha=.5
figure
ylp=y
  for i=1:500
  ylp=alpha*ylp(2:10001-i)+(1-alpha)*ylp(1:10000-i);
plot(ylp);
hold on;
plot(y,'r');
end




