How can I calculate ensemble average of 6 2D matrices with nanmean function?

6 views (last 30 days)
Dear All,
I have 6 2D matrices. Both of them have 10958 rows and 30471 columns. The rows are the time and the columns are the space. I would like to calculate the ensemble time average of these martices using with nanmean function. I tried the following way:
pr_h1=repmat(NaN, 10958);
pr_h=repmat(NaN,size(pr_loci_MPI_ESM_LR_CLM));
>> for j=1:10958
for i=1:30471
pr_h1(j)=[pr_loci_MPI_ESM_LR_CLM(j,i), pr_loci_CM5A(j,i), pr_loci_CNRM_ALADIN(j,i), pr_CNRM_CCLM(j,i), pr_loci_CNRM_CM5_RCA4(j,i), prM_loci_EC_EARTH_RACMO(j,i)];
pr_h(j,:)=nanmean(pr_h1(j));
end
end
but I got the error:
In an assignment A(:) = B, the number of elements in A and B must be the same.
I would appreciate if someone helped me!

Answers (1)

Star Strider
Star Strider on 4 May 2016
I can’t follow your code.
See if this does what you want:
M1 = randi(9,10, 15);
M2 = randi(9,10, 15);
M3 = randi(9,10, 15);
M4 = randi(9,10, 15);
M5 = randi(9,10, 15);
M6 = randi(9,10, 15);
MC = cat(3, M1, M2, M3, M4, M5, M6);
EnsAvg = nanmean(MC, 3);
  2 Comments
Star Strider
Star Strider on 5 May 2016
Yes, but it’s not pretty:
Mlist = {'M1','M2','M3','M4','M5','M6'}; % Matrix Names Cell Array
EnsAvg = zeros(size(M1));
for k1 = 1:6
Mcat = cat(3, EnsAvg, eval(Mlist{k1}));
EnsAvg = nansum(Mcat,3);
end
EnsAvg = EnsAvg/6;
This avoids creating the (10958 x 30471 x 6) concatenated matrix at the expense of using eval, that not everyone here likes. (It has its uses, though, if it’s not abused.)
I checked with my test matrices and my previous code, and the ‘EnsAvg’ results are identical.
Note This only works with the mean. It would have to be modified significantly to calculate the variance, and I’m not certain that would even be possible in the presence of NaN values.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!