How to make moving average filter in an array with window size 100 and 50 overlapped elements?

1 view (last 30 days)
The question goes like this:
I have an array of size 20000*1. I want to apply moving average filter of 2 types.
Type 1. Average of each 100 elements. e.g. 1:100, 101:200, 201:300, and so on
Type 2. Average of each 100 elements with 50 overlapped. e.g. 1:100, 51:150, 101:151, and so on
How can I do it, can anyone help please?

Answers (2)

Jos (10584)
Jos (10584) on 25 May 2016
Edited: Jos (10584) on 25 May 2016
This is not truly a moving average filter, but averaging the array by chunks. This is a nice job for arrayfun:
A = rand(2000,1)
N = numel(A)
OUT1 = arrayfun(@(k) mean(A(k:min(k+99,N))), 1:100:N)
OUT2 = arrayfun(@(k) mean(A(k:min(k+99,N))), 1:50:N)

Guillaume
Guillaume on 25 May 2016
Edited: Guillaume on 25 May 2016
Type 1: reshape into rows of 100 hundred elements and average. This should be a lot faster than arrayfun:
out1 = mean(reshape(A, 100, []))
Type 2: slightly more complicated, interleave the offseted array in the previous result:
out2 = [0, mean(reshape(A(51:end-50), 100, [])); ...
mean(reshape(A, 100, []))];
out2 = out2(2:end)
Both solutions assume that the array size is multiple of 100.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!