%%LMS滤波算法
%采用输入周期波形,人工加噪,白噪声和高斯白噪声,再采用LMS算法进行滤波。
clear;
clc;
grid off;
%周期信号的产生
t=0:pi/100:4*pi;
sn= sin(2*3.14 *t);
t=0:pi/100:4*pi;
%t=0:pi/100:6*pi;
%t1=2*pi
%t2=4*pi
%t3=6*pi
%sn1=sin(1*pi*t).*(t>=0&t<=t1)
%sn2=sin(3*pi*t).*(t>=t1&t<=t2)
%sn3=sin(6*pi*t).*(t>=t2&t<=t3)
figure(1)
subplot(3,1,1)
plot(t,sn);
title('原始的周期信号')
grid on;
%噪声信号的产生
%randn('state',sum(100*clock));
%noise =randn(1,100);
noise =0.2*rand(size(t)) %均匀白噪声
noise1 =0.2*randn(size(t)) %高斯白噪声
highfrequency=sin(400*2*pi*t)
subplot(4,1,2)
plot(t,noise);
title('均匀白噪声信号');
subplot(4,1,3)
plot(t,noise1);
title('高斯噪声信号');
subplot(4,1,4)
plot(t,highfrequency);
title('高频噪声信号');
grid on;
%信号滤波
xn=sn +noise+highfrequency;
xn=xn +noise1; %加了高斯白噪声后滤波效果不好
xn=xn.';
dn=sn.'; %把原始信号作为参考信号
M=50;
figure(2)
subplot(2,1,1)
plot(t,xn)
title('加噪声后的信号波形')
grid on
%初始化
r_max =max(eig(xn*xn.'));
mu =rand()/r_max;
%mu = 0.01; %mu越小,滤波器幅值越低
itr =length(xn); %100个点
en=zeros(itr,1); %en是矩阵 100行一列
w=zeros(M,itr); %20*100矩阵
%LMS滤波算法
%d(n)期望信号
%y(n)输出信号
%e(n)误差信号
%输入信号x(n)
for k=M:itr %第20到第100的点进行滤波 % 第k次迭代
x = xn(k:-1:k-M+1); % 滤波器M个抽头的输入
% x = xn(k:-1:k-M+1);
y=w(:,k-1).'*x %y(n)=Σw(n) *x(n-k) 滤波器的输出
en(k)=dn(k)-y ; % 第k次迭代的误差
%加权因子 % 滤波器权值计算的迭代式
w(:,k)=w(:,k-1)+2*mu*en(k)*x
end
%yn=inf*ones(size(x(n)));
yn = inf * ones(size(xn));
for k=M:itr
x=xn(k:-1:k-M+1);
yn(k)=w(:,end).' *x;
end
%画图
subplot(2,1,2)
plot(t,yn)
title('滤波器输出信号')
grid on;
figure(3);
hold on;
plot(t,dn,'g',t,yn,'b',t,dn-yn,'r');
grid on;
legend('期望输出','滤波器输出','误差')
%c=max(dn-yn)
%LMS输出的偏差会越来越小
评论0