Working with NaN in matlab Functions

I was wondering if Matlab has a built-in way to work with NaN in function calls. In particular, I am trying to take the average value of a vector in which there is NaN . For example, in R

 > x = c(1,2,3,4,NA) > mean(x) [1] NA > mean(x,na.rm=TRUE) [1] 2.5 

Is there anything acceptable for this in Matlab that is on the same line (I do not want to write my own function and should not go in cycles to find NaN before calculating the average value).

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

+3
source share
4 answers

You can do something like mean(x(~isnan(x))) . If you want, you can also write a bunch of wrappers like this and put them in the startup.m file.

+3
source

In MATLAB 2015a, mean supports the optional nanflag parameter . Using the example from JoErNanO's answer,

 A = [1 0 NaN; 0 3 4; 0 NaN 2]; mean(A, 'omitnan') % = [0.333333333333333 1.5 3] 

The default for this parameter is includenan , which will return NaN for columns / rows containing NaN s.

median , cov , min , max , sum , var and std also support ignoring NaN s.

+3
source

I think this should work:

 mean(x(isfinite(x))); 
+2
source

What about Matrices?

As Kartik V shows,

 mean(x(~isnan(x))) 

will work for vectors. However, if you have an n-by-m matrix and want to calculate the standard deviation of the random NaN, you will have to run a for loop.

Scenario example

Imagine a data matrix of the form:

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

Running mean(A(~isnan(A))) gives:

 ans = 1.4286 

This is due to the fact that logical indexing effectively "aligns" the matrix into a vector.

Looping Solution (Column Average)

Assuming you want to calculate the average of a column, the loop solution will look like this:

 % Preallocate resulting mean vector nCols = size(A, 2); mu = zeros(1, nCols); % Compute means for col = 1:nCols mu(col) = mean(A(~isnan(A(:, col)), col)); end 

Result:

 mu = 0.3333 1.5000 3.0000 

Looping Solution (cross section average)

Assuming you want to calculate the rms value, the loop solution will look like this:

 % Preallocate resulting mean vector nRows = size(A, 1); mu = zeros(nRows, 1); % Compute means for row = 1:nRows mu(row) = mean(A(row, ~isnan(A(row, :)))); end 

Result:

 mu = 0.5000 2.3333 1.0000 
+2
source

All Articles