%Lecture_041812.m

dt = .001;  %step size
maxt = 5;  
t = 0:dt:maxt;
nt =length(t);
k =1;

s = zeros(size(t));

ti = [0,1,2]; %seconds

ii = floor(ti/dt)+1;


s(ii) = 1/dt;

y=zeros(size(t));

% for i=1:(nt-1)
%     dy = (s(i) - y(i)/k)*dt;
%     y(i+1) = y(i)+dy;
% end

y = leakyIntegrator(s,k,t);



figure(1)
subplot(2,1,1)
plot(t,s,'r-')
xlabel('Time (s)');
ylabel('Imput');
set(gca,'XLim',[0,maxt]);

subplot(2,1,2)
plot(t,y,'b-')
xlabel('Time (s)');
ylabel('Output');
set(gca,'XLim',[0,maxt]);

%% predicting the response to any input

id = logical(floor(rand(size(t))+.01));

s = zeros(size(t));
s(id) = 1/dt;


s =s.*rand(size(s));

s = sin(2*pi*t*.5);


y = leakyIntegrator(s,k,t);

figure(1)
clf
subplot(2,1,1)
plot(t,s,'r-')
xlabel('Time (s)');
ylabel('Imput');
set(gca,'XLim',[0,maxt]);

subplot(2,1,2)
plot(t,y,'b-')
xlabel('Time (s)');
ylabel('Output');
set(gca,'XLim',[0,maxt]);

% calculate the impulse reponse function


impulse = zeros(size(t));
impulse(1) = 1/dt;

r = zeros(1,nt*2);
h = zeros(size(t));
for i=1:length(t)
    id = i:(i+nt-1);
    r(id) = r(id) + s(i)*h*dt;
end
r = r(1:nt);


hold on
plot(t,r,'r.');

%% convolution

rconv = conv(s,h)*dt;
rconv=rconv(1:nt);
plot(t,rconv,'g.'); 


%% cascade of leaky integrators

dt = .01;  %step size
maxt = 60;  
t = 0:dt:maxt;
nt =length(t);
k =1;

n = 4;  %number of cascades

impulse = zeros(size(t));
impulse(1) = 1/dt;
h = impulse;
for i=1:n
    h = leakyIntegrator(h,k,t)/k;
end

figure(2)
clf
plot(t,h,'b-')
xlabel('Time (s)');
ylabel('Response');
set(gca,'XLim',[0,maxt]);

%% sinusoids
freq = .1;
s = sin(2*pi*freq*t);

y = conv(s,h)*dt;
y = y(1:nt);

figure(3)
clf
subplot(2,1,1)
plot(t,s,'r-')
xlabel('Time (s)');
ylabel('Imput');
set(gca,'XLim',[0,maxt]);

subplot(2,1,2)
plot(t,y,'b-')
xlabel('Time (s)');
ylabel('Output');
set(gca,'XLim',[0,maxt]);





