Thread Subject: NaN Result from Loop

Subject: NaN Result from Loop

From: Parker Clark

Date: 20 Nov, 2009 03:20:18

Message: 1 of 3

I am writing a program to calculate and model the movement of particles based on external forces, and in one of my for loops the addition of two doubles results in NaN.

sumFx = sumFx + dir(1)*(k*q(i)*q(k)/norm(diff)^2)

The second half of the equation never returns NaN and the initial value of sumFx is 0. If either the first half or the second half is replaced with '1' the NaN result is avoided. How can two doubles create NaN?

Subject: NaN Result from Loop

From: Matt Fig

Date: 20 Nov, 2009 03:44:06

Message: 2 of 3

Put this If statement in your For loop after the shown:

sumFx = sumFx + dir(1)*(k*q(i)*q(k)/norm(diff)^2);

if isnan(sumFx)
   [dir(1) k q(i) q(k) norm(diff)^2]
end

This will tell you where the problem lies; you should be able to trace it back from there.

Subject: NaN Result from Loop

From: Steven Lord

Date: 26 Nov, 2009 22:20:35

Message: 3 of 3


"Matt Fig" <spamanon@yahoo.com> wrote in message
news:he53a6$s0j$1@fred.mathworks.com...
> Put this If statement in your For loop after the shown:
>
> sumFx = sumFx + dir(1)*(k*q(i)*q(k)/norm(diff)^2);
>
> if isnan(sumFx)
> [dir(1) k q(i) q(k) norm(diff)^2]
> end
>
> This will tell you where the problem lies; you should be able to trace it
> back from there.

You can also use the Debugger to stop execution of the code when a NaN or
Inf occurs:

http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/brqxeeu-175.html#brqxeeu-242

Or use "dbstop if infnan" or "dbstop if naninf".

To answer Parker's other question, "How can two doubles create NaN?": since
you're using multiplication and division, 0*Inf will result in NaN, as will
0/0 or Inf/Inf.

--
Steve Lord
slord@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ

Tags for this Thread

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Tag Activity for This Thread
Tag Applied By Date/Time
nan Parker Clark 19 Nov, 2009 22:34:21
for loop Parker Clark 19 Nov, 2009 22:34:21
rssFeed for this Thread

Contact us at files@mathworks.com