Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

how to catch unwanted NaN and Inf

Asked by John Hopkins on 6 Jan 2013

I sometimes unknowingly generate values which are NaN and later on it may cause unexpected problems. I want to catch occurances of NaN or Inf without manually inserting isnan and isinf everywhere. When I use

dbstop if naninf

I have the following problem: dbstop will stop in all sorts of built-in matlab functions. But I only want dbstop to stop when it finds NaN or inf in a variable that is in the scope of the main function I wrote. How do I change this or is there an alternate way to catch unwanted occurances of NaN/inf? Thanks.

0 Comments

John Hopkins

Tags

Products

No products are associated with this question.

1 Answer

Answer by Matt J on 7 Jan 2013
Edited by Matt J on 7 Jan 2013

If it's a particular variable you're interested in, you can set a conditional breakpoint using a dbstop syntax like

 dbstop in file if any(isnan(A(:))

Or you can set the breakpoint GUI-style in the MATLAB editor as described here http://www.mathworks.com/help/matlab/matlab_prog/debugging-process-and-features.html#brqxeeu-234.

7 Comments

Matt J on 10 May 2013

ISINF works like this:

    >> isinf([1,2,3, Inf, 4 5])
    ans =
         0     0     0     1     0     0

To find NaNs as well, best to use ~isfinite()

    >> ~isfinite([NaN,2,3, Inf, 4 -Inf])
    ans =
         1     0     0     1     0     1
Image Analyst on 10 May 2013

What do you want to do with them once you find (if you find) nans and infs? Set them to some other value? Remove them totally from the vector (shortening the vector)?

Habib on 11 May 2013

If the execution stops at a nan, I am able to see what caused that and I can repair it. I have functions calling functions and above all a fzero is utilized inside another fzero... . It is not easy to manually track everything to find possible nan/infs. I face errors by fzero, and it takes quite some time to realize that oh, it origins from a nan in value. You know sometimes returned error messages are missleading.

... I aksed a question yesterday and Matt J, tried my coed and apparently something is wrong with my Matlab installation. It causes dbstop if naninf doesnt work correctly. I have to reinstall or upgrade first.

Matt J

Contact us