%Demo done during Session 6 illustrating
%adaptive equalization for digital communications.
clear all
clf
set(0,'defaultaxesfontsize',22);
Nb=256;
q=[-.1 .25 1 -.3 .2];
%generate random bits of information
a=ones(1,Nb);
temp=rand(1,Nb);
a(find(temp>.5))=-1;
N2=10;
M1=2;  M2=2;
Md=N2-M2;
x=zeros(1,Nb+N2+M1);
for n=(M1+Md):(Nb+M1+Md-1);
x(1,n-M1:n+M2)=x(1,n-M1:n+M2)+a(1,n-M1-Md+1)*q;
end
%estimation of optimal filter coefficient vector
%based on block time-averaged estimates of Rxx and rdx
M=M1+1+N2;
Rxx=zeros(M,M);
rdx=zeros(M,1);
w=1; alpha=1/w;
for n=(M1+Md+1):(Nb+M1+Md);
Rxx=Rxx+x(1,n+M1:-1:n-N2).'*x(1,n+M1:-1:n-N2);
rdx=rdx+a(1,n-M1-Md)*x(1,n+M1:-1:n-N2).';
end
%initial filter coefficient vectors for LMS and RLS
hest=inv(Rxx)*rdx;
hlms=[zeros(M1,1) ; 1; zeros(N2,1)];
hrls=hlms;
rxx0=x*x.'/(M1+M2+Nb);
Rxx=Rxx/Nb;
mu=2/(4*trace(Rxx));
Rinv=0.1*eye(M,M);
%iterating over successive data blocks of length M
for n=(M1+Md+1):(Nb+M1+Md);
y(1,n-M1-Md)=x(1,n+M1:-1:n-N2)*hest;
%LMS adaptation
ylms(1,n-M1-Md)=x(1,n+M1:-1:n-N2)*hlms;
errlms=a(1,n-Md-M1)-ylms(1,n-M1-Md);
hlmsold=hlms;
hlms=hlmsold+mu*errlms*x(1,n+M1:-1:n-N2).';
%RLS adaptation
hrlsold=hrls;
errrls=a(1,n-Md-M1)-x(1,n+M1:-1:n-N2)*hrlsold;
Rinvold=Rinv;
f=Rinvold*x(1,n+M1:-1:n-N2).';
murls=x(1,n+M1:-1:n-N2)*f;
Kvec=f/(w+murls);
Rinv=alpha*(Rinvold-Kvec*f.');
hrls=hrlsold+errrls*Kvec;
yrls(1,n-M1-Md)=x(1,n+M1:-1:n-N2)*hrls;
end
Nl=16;
plot(x(1,Md+M1:Nb+Md+M1),zeros(size(x(1,Md+M1:Nb+Md+M1))),'r+','MarkerSize',18,'Linewidth',3);
axis([-2 2 -2 2]);
legend('Distored Bit Values');
title('Received Signal Constellation');
pause
plot(y,zeros(size(y)),'kx','MarkerSize',18,'Linewidth',3);
axis([-2 2 -2 2]);
legend('Block Estimate');
title('Estimated Signal Constellation');
pause
plot(yrls(1,Nl:Nb),zeros(size(yrls(1,Nl:Nb))),'mo','MarkerSize',18,'Linewidth',3);
axis([-2 2 -2 2]);
legend('RLS Estimate');
title('Estimated Signal Constellation');
pause
plot(ylms(1,Nl:Nb),zeros(size(ylms(1,Nl:Nb))),'r+','MarkerSize',18,'Linewidth',3);
axis([-2 2 -2 2]);
legend('LMS Estimate');
title('Estimated Signal Constellation');

