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?
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.
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.
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'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With