Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mean filter in MATLAB without loops or signal processing toolbox

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

like image 262
Doresoom Avatar asked Apr 02 '10 20:04

Doresoom


People also ask

What is average filter in Matlab?

The averaging_filter. m function acts as an averaging filter on the input signal; it takes an input vector of values and computes an average for each value in the vector. The output vector is the same size and shape as the input vector.

What is Signal Processing Toolbox in Matlab?

Signal Processing Toolbox™ provides functions and apps to manage, analyze, preprocess, and extract features from uniformly and nonuniformly sampled signals. The toolbox includes tools for filter design and analysis, resampling, smoothing, detrending, and power spectrum estimation.


1 Answers

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

like image 94
merv Avatar answered Oct 26 '22 19:10

merv