I was wondering if matlab has a built in way to deal with NaN
's in function calls. More specifically, I am trying to take the mean of a vector that has a NaN
in it. 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 something comprable to this in Matlab that is in one line (I don't want to write my own function nor have to loop to find NaN
's before calculating the mean).
Also, I do not have access to the statistics toolbox so I can't use something like nanmean()
.
What about Matrices?
As Karthik V suggests,
will work for vectors. However in case you have an n-by-m matrix and wish to compute the row-/column-wise mean discarding occasional NaN's you will have to run a for loop.
Sample Scenario
Imagine a data matrix of the form:
Running
mean(A(~isnan(A)))
yields:This is because the logical indexing effectively "flattens" the matrix into a vector.
Looping Solution (Column-wise Mean)
Assuming you want to compute the column-wise mean, the looping solution then becomes:
Resulting in:
Looping Solution (Row-wise Mean)
Assuming you want to compute the row-wise mean, the looping solution then becomes:
Resulting in:
As of MATLAB 2015a,
mean
supports an extra parameter,nanflag
. Using the example from JoErNanO's answer,The default for that parameter is
includenan
, which will returnNaN
for columns/rows containingNaN
s.median
,cov
,min
,max
,sum
,var
andstd
also support ignoring ofNaN
s.I think this should work:
You could do something like
mean(x(~isnan(x)))
. If you want you could also write a bunch of wrappers like this and put them in your startup.m file.