Taking the average of the matrix with NaN in Matlab

Possible duplicate:
Working with NaN in matlab Functions

Is there one line of command that allows you to take the average value of a matrix element (ignoring NaN 's) in Matlab? For instance,

 >> A = [1 0 NaN; 0 3 4; 0 NaN 2] A = 1 0 NaN 0 3 4 0 NaN 2 

So mean(A) should be (1+3+2+4+0+0+0)/7 = 1.4286

In addition, I do not have access to the statistics toolbar, so I can not use nanmean()

+4
source share
2 answers

You can use isnan() to filter out unwanted elements:

 mean(A(~isnan(A))) 
+5
source
 nanmean 

Runs the same as mean , but ignores nans.

For instance:

 >> A = [1 0 NaN; 0 3 4; 0 NaN 2] A = 1 0 NaN 0 3 4 0 NaN 2 >> nanmean(A) ans = 0.333333333333333 1.5 3 >> nanmean(A,2) ans = 0.5 2.33333333333333 1 >> nanmean(A(:)) ans = 1.42857142857143 
+2
source

All Articles