2010-04-02 89 views
6

我需要在數據集上實現平均濾波器,但我無法訪問信號處理工具箱。有沒有辦法做到這一點,而不使用for循環?下面是我有工作代碼:MATLAB中的平均濾波器無環或信號處理工具箱

x=0:.1:10*pi;  
noise=0.5*(rand(1,length(x))-0.5); 
y=sin(x)+noise;  %generate noisy signal 
a=10;    %specify moving window size 
my=zeros(1,length(y)-a); 
for n=a/2+1:length(y)-a/2 
    my(n-a/2)=mean(y(n-a/2:n+a/2));  %calculate mean for each window 
end 
mx=x(a/2+1:end-a/2);     %truncate x array to match 

plot(x,y) 
hold on 
plot(mx,my,'r') 

編輯:

實施Merv的解決方案後,內置的過濾方法滯後於原始信號。有沒有解決的辦法? alt text

回答

5

使用內置FILTER功能

%# generate noisy signal 
x = sin(0:.1:10*pi); 
x = x + 0.5*(rand(1,length(x))-0.5); 

%# moving average smoothing 
window = 15; 
h = ones(window,1)/window; 
y = filter(h, 1, x); 

%# plot 
subplot(211), plot(x), ylim([-1 1]), title('noisy') 
subplot(212), plot(y), ylim([-1 1]), title('filtered') 

爲了解決滯後的問題,嘗試這樣的事情:

s = ceil(window/2); 
yy = y(s:end); 
n = length(x); 
plot(1:n, x, 'b'), hold on, plot(1:n-s+1, yy,'r'), hold off 
legend({'noisy' 'filtered'}) 

alt text http://img171.imageshack.us/img171/4510/45062995.png