Effacer les filtres
Effacer les filtres

How do I calculate the mean entry value of multiple 3d matrices, excluding NaN/0?

3 vues (au cours des 30 derniers jours)
zhen
zhen le 10 Jan 2018
Commenté : zhen le 10 Jan 2018
I have 4 3D matrices of the same size (40x40x22), and I would like to have an matrix 40x40x22 with the mean entries, while excluding 0/NaN values.
I tried doing:
meanMatrix = (Matrix1 + Matrix2 + Matrix3 + Matrix4)/4
which is close, but does not exclude 0/NaN values.
Is there an actual function which allows to do it with 3d matrices? It's not possible to concatenate the 3D matrices (unlike a 2D matrix) and calculate its mean.
Would it be possible to calculate the mean of every entry using a cell array?

Réponse acceptée

Jan
Jan le 10 Jan 2018
Modifié(e) : Jan le 10 Jan 2018
If you have your matrices in a cell array instead using indices hidden in the name of the variables, the solution would be easier. But it works:
M = cat(4, Matrix1 + Matrix2 + Matrix3 + Matrix4);
M(isnan(M)) = 0;
meanM = sum(M, 4) ./ sum(M ~= 0, 4);
Instead of dividing the sum by the number of matrices, you divide by the number of non-zero elements. The NaNs vanish in the sum, if you replace them by zeros.
You had the right idea already, but stopped too early:
It's not possible to concatenate the 3D matrices
(unlike a 2D matrix) and calculate its mean.
  1 commentaire
zhen
zhen le 10 Jan 2018
We actually tried the concatenation, but it did not work at first saying that the matrices were of different dimensions, but now it does! Thank you for your help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by