2

While using the isnan(x) operator, I notice that the output is an array with 0s and 1s corresponding whether the element is NaN or not.

The logical way to filter out NaN elements would be x(find(~isnan(x))), as find() returns the indices. As a suprise to me, x(~isnan(x)) also gives the same result.

On checking, ~isnan(x) is just an array of 1s and 0s, and for the simple case of x = rand(10,1), I get all(~isnan(x) == ones(10, 1)) as true. But when I run x(ones(10, 1)), I get an array with just the first element of x repeated 10 times, as expected.

What am I missing here?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Dhruv Shah
  • 130
  • 1
  • 1
  • 5

1 Answers1

4

MATLAB uses multiple type of indices.

isnan returns logical indices. That is, a matrix or vector of size x where it is 1 if that element is nan. The output is logical "binary" variable

find looks for any element that is not 0 and gives you its index. The output are integers.

As such, both outputs can be used as indices so they will the same result. That being said, if you don't need the actual indices (which you don't in your example above), don't use it. find is slow and redundant in the case above.

Now if you create the arrays of 1s like you did above, it treats it as an index (like find) so it returns the value of the first element 10 times. The reason is that the functions ones does not return a logical variable but actual numbers (real). If you substitute ones with true or convert the results into binary first, it will be treat it as logical indices.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
MosGeo
  • 1,012
  • 9
  • 9