简体   繁体   中英

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.

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
   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
   yd(i)=w*x'; 
  e(i) = d(i) - w * x';
 for m=1:N
 w(m) = w(m) + mu * e(i) * x(m);
  end
 end
    subplot(221),plot(t,d),ylabel('Desired Signal'),
  sub plot(222),plot(t,x),ylabel('Input Signal+Noise'),
  subplot(223),plot(t,e),ylabel('Error'),
  subplot(224),plot(t,yd),ylabel('Adaptive Desired output')

What you were missing was the multiplication of error term in a single iteration with each sample of input and separate update of weights

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM