# How can I average multiple matrices by element, ignoring NaN values, to create a new matrix of the same size?

9 views (last 30 days)
Patrick on 16 Oct 2013
Commented: Jerry Gregoire on 14 Apr 2015
I have 248 matrices, each of size 72x144. There are some NaN values inserted randomly here and there in these matrices. I would like to create a new matrix, also of size 72x144, 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?
Patrick on 16 Oct 2013
There are no elements as zero, only NaN.

Yannick on 16 Oct 2013
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);
##### 2 CommentsShow 1 older commentHide 1 older comment
Jerry Gregoire on 14 Apr 2015
You can also use mean with 'omitnan'
S = mean(..., MISSING) specifies how NaN (Not-A-Number) values are
treated. The default is 'includenan':
'includenan' - the mean of a vector containing NaN values is also NaN.
'omitnan' - the mean of a vector containing NaN values is the mean
of all its non-NaN elements. If all elements are NaN,
the result is NaN.

Azzi Abdelmalek on 16 Oct 2013
Edited: Azzi Abdelmalek on 16 Oct 2013
Edit
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]
A={matrixA matrixB matrixC}
B=cat(3,A{:})
idx=find(isnan(B))
C=ones(size(B));
C(idx)=0;
B(idx)=0;
out=sum(B,3)./sum(C,3)
Patrick on 16 Oct 2013
Thank you for your help Azzi, I have solved the problem.