Jeremy McNees
Jeremy McNees

Reputation: 787

Matlab returning only NANs from a vector that has NaNs and non-NaNs

I have simulation data in a vector of size 50,000 x 1, which has NaNs and non-NaNs. I would like to average the non-NaNs, but the function nanmean returns NAN. I have tried removing the NANs, but I only get a vector of zeros. Visual inspection of the vector leads me to doubt that the true mean of this vector is really NaN.

Also, I would like to use this vector to compute covariance with several other vectors (at some point). My alternative is doing this in Excel, which would be painful.

Any thoughts?

Thank you

Upvotes: 0

Views: 251

Answers (2)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Assuming you have a vector that only contains finite numeric values, and a NaN here and there, the solution is very simple

nanmean(A)

This should only bring trouble if there are non finite values in your vector. In this case you could filter them out as suggested by @Ryan, but then you need to realize that you are not actually calculating the mean of the vector.

Ask yourself whether you may instead be interested in something like

nanmedian(A)

About the calculation of covariances and the likes, assuming you have vectors v and w, then I would recommend you to do something like this:

idx = isfinite(v) & isfinite(w);
cov(v(idx),w(idx))

Upvotes: 0

Ryan J. Smith
Ryan J. Smith

Reputation: 1140

Let's say your data in stored in a vector A, you can take the mean of the vector excluding the NaNs as well as any Inf and -Inf values via:

meanA = mean( A(isfinite(A)) );

Upvotes: 7

Related Questions