% SVD8  Laguerre approximation
% Question: finding the MSE in time is the same as finding the
% MSE for the adjustable parameters????
% uses the samples of the segment that collects the charge,
% 

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

for i=1:19
 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';

for i=1:I(1,2)
  t(:,i)=invutuut*Y(:,i);
  y_hat(:,i)=u*t(:,i);
  mse(i)=[Y(:,i)-y_hat(:,i)]'*[Y(:,i)-y_hat(:,i)];
%figure(1),plot(1:DL,Y(:,i),'r',1:DL,y_hat(:,i),'g')
%pause(1)
end

%sum(mse)

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

%measured
M=2*Y(:,1)+3*Y(:,11);
Mn=2*Yn(:,1)+3*Yn(:,11);

%   find mse for time sequence
mse=.1*ones(I(1,2),I(1,2));
for i=1:I(1,2)
 for j=1:I(1,2)
  if i~=j
   g=inv([Yn(:,i)';Yn(:,j)']*[Yn(:,i),Yn(:,j)])*[Yn(:,i)';Yn(:,j)']*Mn;  
   mse(i,j)=[Mn-g(1)*Yn(:,i)-g(2)*Yn(:,j)]'*[Mn-g(1)*Yn(:,i)-g(2)*Yn(:,j)];
  end
 end
end


invutuutn=inv(un'*un)*un';
%find the Laguerre parameters for the measured signal.
Mt=invutuutn*Mn;
%M_hat=u*Mt;
%mse=[M-M_hat]'*[M-M_hat]

%   find mse for Laguerre parameter sequence
mset=1*ones(I(1,2),I(1,2));
for i=1:I(1,2)
 for j=1:I(1,2)
  if i~=j
   g=inv([t(:,i)';t(:,j)']*[t(:,i),t(:,j)])*[t(:,i)';t(:,j)']*Mt;  
   mset(i,j)=[Mt-g(1)*t(:,i)-g(2)*t(:,j)]'*[Mt-g(1)*t(:,i)-g(2)*t(:,j)];
%figure(1),plot(1:20,Mt,'g',1:20,g(1)*t(:,i)+g(2)*t(:,j),'r')
%pause(1)
  end 
 end
end


[z,w]=min(mse);
[zt,wt]=min(mset);

