# How to Implement the moving average filter in time domain in MATLAB? [closed]

I have a sinusoidal x(t) = sin(500πt) signal is corrupted by random noise. The corrupted signal is sampled with sampling frequency fs = 5 kHz and passed through a 5-point moving average filter to reduce the noise. I have written the following MATLAB Code for the same:-

fs=5e3; t=0:1/fs:0.02;
x=sin(2*pi*250*t);           % uncorrupted signal

r=0.1*randn(1,length(x));    % random noise
XR=x+r;                      % signal + noise (filter input)

y=0;
% Implement the moving average filter in time domain
for n=5:length(XR),          % M = 5
y(n) =                   % missing code using the command 'sum'
end

figure(12);
subplot(211); plot(t,XR,t,x,'r'); legend('Corrupted','Original');
xlabel('time (sec)'); ylabel('Amplitude'); grid;

subplot(212); plot(t,y,'k',t,x,'r'); legend('After filtering','Original');
xlabel('time (sec)'); ylabel('Amplitude');grid;


But, I am not sure how to implement the moving average filter in time domain using sum command to get the output (y[n]) in the for loop as mentioned above in the code. Any suggestions would be highly appreciated! Thanks a lot for the help🙏

• Is that homework? Than please tag it as that Mar 20, 2021 at 15:20
• I like how you have all the code, including the subplot() & co, but you don't have that particular line. Mar 20, 2021 at 16:08
• @aconcernedcitizen Yeah cause that's an assignment question I got, and I am not asking the answer just for some suggestions/hints:) Mar 20, 2021 at 16:12

HINT (really an answer but not providing code so its a hint):

In your setup, a $$M$$-point moving average filter uses the average of the previous $$M-1$$ samples and the current sample to compute the current output. So for $$n=5$$, the output will be $$\frac{1}{5}(x[1]+x[2]+x[3]+x[4]+x[5])$$. In general, for $$n=k$$ the output of this $$M$$-point MA filter is:

$$\frac{1}{M}\sum_{n=k-M+1}^kx[k]$$

• Thanks for the help! Appreciate it:)🙏😊 Mar 20, 2021 at 16:49

A 5-point moving average can be performed in different ways. The two principal options consist in:

1. causal: take the current point, and average it with the four most recent past samples, or sum it and divide by the length of the average span (which seems to be your choiice, regarding your for bounds $$y[n] = \left(\sum^n_{k=n-4} x[k]\right)/5\,,$$
2. symmetric: take the current point, and average it with two samples of the left and two on the right $$y[n] = \left(\sum^{n+2}_{k=n-2} x[k]\right)/5\,.$$

You can find the most classical Matlab solutions by yourself, using for instance Calculate moving average manually. A last option could be more recursive, and implementable (with proper initialization) as:

z(n) =  sum([z(n-1),XR(n)/5-XR(n-5)/5]);


which might be your next exercise.