MATLAB: How to compute centered moving average from an NxM array

matrix array

Hello:
I have an 40×2 matrix, in which the first column shows day index and the 2nd column value for each day:
1 11
2 12
3 10
4 10
5 12
6 11
7 12
8 10
9 12
10 10
11 12
12 12
13 10
14 9
15 12
16 12
17 12
18 11
19 10
20 10
21 11
22 11
23 10
24 8
25 9
26 9
27 9
28 8
29 8
30 12
31 11
32 9
33 9
34 12
35 11
36 11
37 10
38 10
39 11
40 9
How to compute centered moving average with 30 days moving window taking 15th of the day as the midpoint and traversing backward 14 days and forward 15 days? Basically I want to compute: Xavg = median[X(i-14):X(i+15)]. where X(i) is the data point and Average is the averaging operator. I found a few thread using convolution operator but could not find out how to fix step size since my mid point is located on the 15th day and further how to compute median effect?

Best Answer

You can use movmean() and discard the endpoints
M = [
1 11
2 12
3 10
4 10
5 12
6 11
7 12
8 10
9 12
10 10
11 12
12 12
13 10
14 9
15 12
16 12
17 12
18 11
19 10
20 10
21 11
22 11
23 10
24 8
25 9
26 9
27 9
28 8
29 8
30 12
31 11
32 9
33 9
34 12
35 11
36 11
37 10
38 10
39 11
40 9];
avg_val = movmean(M(:,2), 30, 'Endpoints', 'discard')