Azzera filtri
Azzera filtri

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

3 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Jan
Jan il 10 Gen 2018
Modificato: Jan il 10 Gen 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 Commento
zhen
zhen il 10 Gen 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!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by