MATLAB: How to average multiple matrices by element, ignoring NaN values, to create a new matrix of the same size

averageby elementmatrixnan

I have 248 matrices, each of size 72×144. There are some NaN values inserted randomly here and there in these matrices. I would like to create a new matrix, also of size 72×144, which is an average by element of the originals, but ignoring the NaN values. For example:
Original:
matrixA = [2 3 5 | 3 NaN 1 | 2 4 3]
matrixB = [3 4 NaN | 1 2 5 | NaN 3 5]
matrixC = [NaN 2 3 | 2 5 3 | 1 2 1]
Want:
matrixAvg = [2.5 3 4 | 2 3.5 3 | 1.5 3 3]
Is there a simple way for me to do this?

Best Answer

Hi, if you have Statistics Toolbox, you can use nanmean as follows:
matrixA = [2 3 5 ; 3 NaN 1 ; 2 4 3];
matrixB = [3 4 NaN ; 1 2 5 ; NaN 3 5];
matrixC = [NaN 2 3 ; 2 5 3 ; 1 2 1];
allData = cat(3,matrixA,matrixB,matrixC);
nanmean(allData,3);