Graviton
Graviton

Reputation: 83254

Find all NaN elements inside an Array

Is there a command in MATLAB that allows me to find all NaN (Not-a-Number) elements inside an array?

Upvotes: 11

Views: 59309

Answers (3)

Marc
Marc

Reputation: 3313

As noted, the best answer is isnan() (though +1 for woodchips' meta-answer). A more complete example of how to use it with logical indexing:

>> a = [1 nan;nan 2]

a =

  1   NaN
NaN     2

>> %replace nan's with 0's
>> a(isnan(a))=0

a =

 1     0
 0     2

isnan(a) returns a logical array, an array of true & false the same size as a, with "true" every place there is a nan, which can be used to index into a.

Upvotes: 24

user85109
user85109

Reputation:

While isnan is the correct solution, I'll just point out the way to have found it. Use lookfor. When you don't know the name of a function in MATLAB, try lookfor.

lookfor nan

will quickly give you the names of some functions that work with NaNs, as well as giving you the first line of their help blocks. Here, it would have listed (among other things)

ISNAN True for Not-a-Number.

which is clearly the function you want to use.

Upvotes: 23

Graviton
Graviton

Reputation: 83254

I just found the answer:

k=find(isnan(yourarray))

k will be a list of NaN element indicies.

Upvotes: 10

Related Questions