Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 3

Matlab Code

LMS Adaptive Noise Cancellation


% Description: % Adaptive filter trained with the LMS algorithm. A sinusoidal % signal corrupted with an unwanted frequency and random noise % is filtered. The desired signal is used to adapt the weights. %--- Filter Parameters --M = 20; % number of taps mu = 0.05; % step-size parameter e_max = 400; % maximum # of epochs %--- Constants --pi = 3.14; Fs = 0.01; % signal frequency Fn = 0.05; % noise frequency %--- Initialize --w = (randn(1,M)-randn(1,M))/100; d = zeros(1,M); u = zeros(1,M); u_out = zeros(1,e_max-M); f_out = zeros(1,e_max-M); % Generate desired signal and input(signal+noise) for t = 1:M-1 d(t) = sin(2*pi*Fs*t); u(t) = d(t)+0.5*sin(2*pi*Fn*t)+0.09*randn; end t = M; epoch = 0; while epoch < e_max % Generate new input input = sin(2*pi*Fs*t); 56 % Shift new input into array for i = 2:M d(M-i+2) = d(M-i+1); u(M-i+2) = u(M-i+1); end d(1) = input; % Add undesired freq & random noise u(1) = input+0.5*sin(2*pi*Fn*t)+0.09*randn; u_out(t-M+1) = u(1); % Compute filter output output = dot(w,u); f_out(t-M+1) = output; %--------------------- LMS Algorithm ---------------------% Compute error

e = d(1) - output; % Update weights for n = 1:M w(n) = w(n)+mu*u(n)*e; end %----------------------------------------------------------in(t-M+1) = u(1); out(t-M+1) = output; err(t-M+1) = e; t = t+1; epoch = epoch +1; %--- Plot noise and filtered signal --subplot(211), plot(t,u(1)), axis([0 e_max -2.5 2.5]), title('Filter Input (Signal + Noise)'), drawnow, hold on subplot(212), plot(t,output), axis([0 e_max -2.5 2.5]), title('Filtered Signal'), drawnow, hold on end

RLS Adaptive Noise Cancellation


% Description: % Adaptive filter trained with the RLS algorithm. A sinusoidal % signal corrupted with an unwanted frequency and random noise % is filtered. The desired signal is used to adapt the weights. 57 %--- Filter Parameters --M = 20; % number of taps delta = 1; lamda = 0.99; e_max = 400; % maximum # of epochs %--- Constants --pi = 3.14; Fs = 0.01; % signal frequency Fn = 0.05; % noise frequency %--- Initialize --w = zeros(M,1); d = zeros(M,1); u = zeros(M,1); P = eye(M)/delta; % Generate desired signal and input(signal+noise) for t = 1:M-1 d(t) = sin(2*pi*Fs*t); u(t) = d(t)+0.5*sin(2*pi*Fn*t)+0.09*randn; end t = M; epoch = 0; while epoch < e_max % Generate new input

input = sin(2*pi*Fs*t); % Shift new input into array for i = 2:M d(M-i+2) = d(M-i+1); u(M-i+2) = u(M-i+1); end d(1) = input; % Add undesired freq & random noise u(1) = input+0.5*sin(2*pi*Fn*t)+0.09*randn; % Compute filter output output = w'*u; %----------------- RLS Algorithm -------------------k = ( P*u )/(lamda+u'*P*u); E = d(1) - w'*u; 58

You might also like