views:

600

answers:

1

I need to implement a mean filter on a data set, but I don't have access to the signal processing toolbox. Is there a way to do this without using a for loop? Here's the code I've got working:

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')

EDIT:

After implementing merv's solution, the built-in filter method lags the original signal. Is there a way around this? alt text

+5  A: 

Use the built-in FILTER function

%# 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')

To solve the lag problem, try something like this:

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

merv

related questions