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:
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.