function [e,n,wo] = lms ( y, x, w, mu )
%
% e = lms ( y, x [, w [, mu ] ] )
%
% least mean square adaptive filter
% 
% Finds e, the difference between y and x filtered using FIR
% filter with initial coefficients w (reversed order). The filter
% is adapted after each sample using the LMS algorithm with
% convergence parameter mu.
%
% The last length(w) output samples of the output are zero.

% Ed Casas, UBC EE, 96/3

	if nargin < 2
		error ( 'usage: e = lms(y,x[,w[,mu]])' ) ;
	end

	N=length(x);

	if length(y) ~= N | N == 0
		error ( 'X and Y must have equal length>0' )
	end

	if nargin < 3
		w=zeros(1,max([4 N/100])) ;
	end

	if nargin < 4
		mu=1/(3*length(w)*sum(x.^2)/N)
	end

	e = zeros(1,length(x)) ;
	lw=length(w)-1;

	for k = 1:N-lw
		e(k)=y(k)-sum(x(k:k+lw).*w) ;
		w=w+2*mu*e(k)*x(k:k+lw);
	end

	if nargout > 1
		n=y-e;
	end

	if nargout > 2
		wo=w ;
	end

end
