分享一个自编的滑动平均代码,和matlab自带的smooth效果一致,直接上代码:
function sm=MA(data,N)
L=length(data);
if rem(N,2)==0
N=N+1;
end
for i=1:L
if i==1
sm(i,:)=data(i);
elseif i==L
sm(i,:)=data(end);
elseif i>1&&i<=floor(N/2)
sm(i,:)=mean(data(1:(i+i-1)));
elseif i<L&&i>=L-floor(N/2)
sm(i,:)=mean(data(end:-1:(i-(L-i))));
else
sm(i,:)=mean(data(i-floor(N/2):(i+floor(N/2))));
end
end
end
clc;
clear;
close all;
data=dlmread('文件地址');
figure
plot(data,'g');
hold on
sm=smooth(data,5);
plot(sm,'r');
hold on
sm2=MA(data,5);
plot(sm2,'--b');
hold on