Search code examples
matlabsequenceaveragerowsskip

Average of numbers in two consequetive sequences using Matlab


I have an array that is 13867 X 2 elements and stored in variable called "data". So, I want to do the following in Matlab:

  • Average (row 1 -> row 21) ; i.e. take the average of first 21 elements
  • Average (row 22 -> row 43) ; i.e. take the average of next 22 elements
  • Average (row 44 -> row 64); i.e. take the average of the next 21 elements
  • Average (row 65 -> row 86); i.e. take the average of the next 22 elements
  • Repeat the process until the end of the matrix, so that we take the average of the last 21 elements from row 13847 to row 13876. I want the average of elements in column 1 and also column 2. I have somehow managed to do that in Excel, but it is a bit cumbersome task (had to create an index for the rows first). I guess at the end we will get 645 averages.

Solution

  • The key to doing that is inserting NaN rows to make the shorter blocks (21 rows) the same size as the longer blocks (22 rows). This is very easy, using the insertrows function from Matlab FileExchange:

    n = 21;
    m = 22;
    
    dataPad = insertrows(data, nan(1,size(data,2)), n:(n+m):size(data,1));
    

    After that, row 22 will be [NaN, NaN], row 66 will be [NaN, NaN], and so on. Now it gets very easy to calculate the mean. Simply reshape this matrix so that all values which should be averaged are on the same column. Finally, use the nanmean function (mean function which simply ignores NaN) to get the result.

    It is not 100% clear to me, whether the result should be 645x2 or 645x1, i.e. whether to average over the rows as well, or not. Here would be the corresponding reshape's for both ways:

    1. Averaging over the rows too:

    dataPadRearr = reshape(dataPad.',m*size(data,2),[]);
    result = nanmean(dataPadRearr,1);
    

    2. Leaving the rows alone:

    dataPadRearr = reshape(dataPad,m,[],size(data,2));
    result = squeeze(nanmean(dataPadRearr,1));
    

    Note that here, you'll need a final squeeze, as the result of nanmean would be of dimension 1x645x2, which is not very practical. squeeze just removes this singleton dimension.