% SVD9  Laguerre approximation
% Question: SVD7: see if we can fit the segment that collects charge 
% by addding more Laguerre waveforms after the curve shape has
% already finish.
% NOW SVD9: test for "dlstep" instead of "dlimpulse"

clear
hold off
% better a=.5
T=.1; a = .4; K = sqrt((1-a^2)*T);
DL=47;
n = [0 K];               %find the outputs of the laguerre polynomial
d = [1 -1*a];
u = dstep(n,d,DL); 
nt = [-a 1];
dt = [1 -a];

for i=1:10
 u = [u dlsim(nt,dt,u(:,i))]; 
end

load shapes2
Y=shapes(:,50+1-DL:50)';
I=size(Y);
y_hat=zeros(I);
invutuut=inv(u'*u)*u';  %to find the best gain on a MSE sense

for i=1:I(1,2)
  theta(:,i)=invutuut*Y(:,i);
  y_hat(:,i)=u*theta(:,i);
  mse(i)=[Y(:,i)-y_hat(:,i)]'*[Y(:,i)-y_hat(:,i)];

%plot(1:DL,y_hat(:,i),'g',1:DL,Y(:,i),'r')
%pause(1)

end

sum(mse)

stop

%New u 'un' matrix with more samples.
un = dimpulse(n,d,140);
for i=1:20
 un = [un dlsim(nt,dt,un(:,i))]; 
end

for i=1:I(1,2)
  Yn(:,i)=un*theta(:,i);

%plot(1:140,Yn(:,i),'g',1:DL,Y(:,i),'r')
%pause(1)

end

invutuutn=inv(un'*un)*un';
for i=1:I(1,2)
  thetan(:,i)=invutuutn*Yn(:,i);
  yn_hat(:,i)=un*thetan(:,i);
  mse(i)=[Yn(:,i)-yn_hat(:,i)]'*[Yn(:,i)-yn_hat(:,i)];

figure(1),plot(1:140,yn_hat(:,i),'g',1:140,Yn(:,i),'r')
pause(1)

end
