Niseonna
Niseonna

Reputation: 181

MATLAB: How do I check if any element in my matrix is nan and do something if that is the case

I know I can use isnan to check for individual elements, such as

for i=1:m
    for j=1:n
        if isnan(A(i,j))
            do something
        end
    end
end

However, instead what I want to do is

 if any(isnan(A))
      do something
 end

When I tried to do this, it doesn't go into the argument because it is considered false. If I just type any(isnan(A)), I just get 1 0 1. So how do I do this?

Upvotes: 7

Views: 12985

Answers (1)

Pursuit
Pursuit

Reputation: 12345

any(isnan(A(:)))

Since A was a matrix, isnan(A) is also a matrix and any(isnan(A)) is a vector, whereas the if statement really wants a scalar input. Using the (:) notation flattens A into a vector, regardless of the initial size.

Upvotes: 8

Related Questions