Filter löschen
Filter löschen

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

3 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

Jan
Jan am 10 Jan. 2018
Bearbeitet: Jan am 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 Kommentar
zhen
zhen am 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!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by