Question

Using MATLAB, how can I find the 3-day moving average of a specific column of a matrix and append the moving average to that matrix? I am trying to compute the 3-day moving average from bottom to top of the matrix. I have provided my code:

Given the following matrix a and mask:

a = [1,2,3;4,5,6;7,8,9;10,11,12;13,14,15;16,17,18];
mask = ones(3,1);

I have tried implementing the conv command but I am receiving an error. Here is the conv command I have been trying to use on the 2nd column of matrix a:

a(:,4) = conv(a(:,2),mask,'valid');

The output I desire is given in the following matrix:

desiredOutput = [1,2,3,5;4,5,6,8;7,8,9,11;10,11,12,14;13,14,15,0;16,17,18,0;]

If you have any suggestions, I would greatly appreciate it. Thank you!

Was it helpful?

Solution

In general it would help if you would show the error. In this case you are doing two things wrong:

First your convolution needs to be divided by three (or the length of the moving average)

c = conv(a(:,2),mask,'valid')/3

c =

     5
     8
    11
    14

Second, notice the size of c. You cannot just fit c into a. The typical way of getting a moving average would be to use same:

a(:,4) = conv(a(:,2),mask,'same')/3

a =

    1.0000    2.0000    3.0000    2.3333
    4.0000    5.0000    6.0000    5.0000
    7.0000    8.0000    9.0000    8.0000
   10.0000   11.0000   12.0000   11.0000
   13.0000   14.0000   15.0000   14.0000
   16.0000   17.0000   18.0000   10.3333

but that doesn't look like what you want.

Instead you are forced to use a couple of lines:

c = conv(a(:,2),mask,'valid')/3;
a(1:length(c),4) = c

a =

     1     2     3     5
     4     5     6     8
     7     8     9    11
    10    11    12    14
    13    14    15     0
    16    17    18     0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top