SKM
SKM

Reputation: 989

How to check for infinity values in Matlab

I have a program which returns 2 variables, denoted as X and Y. The size of X is 3 by 5 andY is 3 by 3. I want to check if the values are infinity or not but Matlab does not do so. In general, this is what I would be doing for any matrix, but this code does not work for the matrix shown in picture. What is the proper way?

clear all


  Y = [

      NaN +    NaNi      NaN +    NaNi      NaN +    NaNi
      NaN +    NaNi      NaN +    NaNi      NaN +    NaNi
      NaN +    NaNi      NaN +    NaNi      NaN +    NaNi];

  if (isnan(Y))
      disp( ' values in Y are infinity')
  end

  X =  1.0e+017 *[

      NaN +    NaNi      NaN +    NaNi      NaN +    NaNi      NaN +    NaNi  -7.8517 - 0.0000i
      NaN +    NaNi      NaN +    NaNi      NaN +    NaNi      NaN +    NaNi  -3.9259 - 0.0000i
      NaN +    NaNi      NaN +    NaNi      NaN +    NaNi      NaN +    NaNi  -1.9629 - 0.0000i];
  if (isnan(X))
      disp( ' values in X are infinity')
  end

Upvotes: 0

Views: 707

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

From help if:

The statements [in the IF's body] are executed if the real part of the [conditional] expression has all non-zero elements.

In your case,

>> isnan(X)
ans =
     1     1     1     1     0
     1     1     1     1     0
     1     1     1     1     0

which would evaluate to false if used as-is in an if condition.

It is usually better to be explicit:

if any(isnan(X(:))
    disp('X contains a NaN'); end

would display the message if there is a NaN anywhere in X, and

if all(isnan(X(:))
    disp('X is all-NaN'); end

would display the message only if all elements in X are NaN.

Also take a look at isfinite - this allows you to detect inf and NaN in one go.

Upvotes: 3

user5871360
user5871360

Reputation:

your code will display values in X are infinity if entire matrix is NaN. if there is even one none-NaN element in your matrix it will display nothing.
If you want a disp( ' values in X are infinity') for every NaN in your matrix, you shall go through the matrix and check each element. Do it with two nested loops:

for i1=1:row
   for j1=1:col
      if (isnan(X(i1,j1)))
         disp( ' values in X are infinity')
      end
   end
end

Upvotes: 0

Related Questions