title: Matlab: How to fix Least Mean square algorithm code
body: <p>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:</p>
  
  <p><a href="http://www.mathworks.com/matlabcentral/fileexchange/35670-lms-algorithm-implementation/content/lms.m" rel="nofollow">http://www.mathworks.com/matlabcentral/fileexchange/35670-lms-algorithm-implementation/content/lms.m</a></p>
  
  <pre><code>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')
  </code></pre>
  
  <p>EDIT</p>
  
  <p>The code from the answer : </p>
  
  <pre><code>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
  </code></pre>
  
  <p>The weight matrix w which stores the coefficients are all zero, meaning that the LMS equations are not working correctly. </p>