Search code examples
matlableast-squares

Matlab: How to fix Least Mean square algorithm code


I am studying about Least Mean Square algorithm and saw this code. Based on the algorithm steps, the calculation of the the error and weight updates looks alright. However, it fails to give the correct output. Can somebody please help in fixing the problem? The code has been taken from:

http://www.mathworks.com/matlabcentral/fileexchange/35670-lms-algorithm-implementation/content/lms.m

clc
close all
clear all

N=input('length of sequence N = ');
t=[0:N-1];
w0=0.001;  phi=0.1;
d=sin(2*pi*[1:N]*w0+phi);
x=d+randn(1,N)*0.5;
w=zeros(1,N); 
mu=input('mu = ');
for i=1:N
   e(i) = d(i) - w(i)' * x(i);
   w(i+1) = w(i) + mu * e(i) * x(i);
end
for i=1:N
yd(i) = sum(w(i)' * x(i));  
end
subplot(221),plot(t,d),ylabel('Desired Signal'),
subplot(222),plot(t,x),ylabel('Input Signal+Noise'),
subplot(223),plot(t,e),ylabel('Error'),
subplot(224),plot(t,yd),ylabel('Adaptive Desired output')

EDIT

The code from the answer :

N = 200;
M = 5;
w=zeros(M,N); 
mu=0.2;%input('mu = ');
y(1) = 0.0;
y(2) = 0.0;
for j = 3:N
 y(j) = 0.95*y(j-1) - 0.195*y(j-2); 
end

x = y+randn(1,N)*0.5;
%x= y;
d = y;
for i=(M+1):N
   e(i) = d(i) -  x((i-(M)+1):i)*w(:,i);
   w(:,i+1) = w(:,i) + mu * e(i) * x((i-(M)+1):i)';
end
for i=(M+1):N
    yd(i) = x((i-(M)+1):i)*w(:,i);  
end

The weight matrix w which stores the coefficients are all zero, meaning that the LMS equations are not working correctly.


Solution

  • I also do not find any mistake in your code. But I doubt that this algorithm is suitable for this kind of noise. You will get better results when using a filter of higher order (M in this case):

    M = 5;
    w=zeros(M,N); 
    mu=0.2;%input('mu = ');
    for i=(M+1):N
       e(i) = d(i) -  x((i-(M)+1):i)*w(:,i);
       w(:,i+1) = w(:,i) + mu * e(i) * x((i-(M)+1):i)';
    end
    for i=(M+1):N
        yd(i) = x((i-(M)+1):i)*w(:,i);  
    end