Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 869
Niseonna Avatar asked Feb 13 '13 20:02

Niseonna


1 Answers

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.

like image 50
Pursuit Avatar answered Nov 15 '22 08:11

Pursuit