step 1) I have created a huge anonymous function, which I call funct. step 2) I calculated a position x3, which is 0.2. When I ask the type, it tells me it is a double, like this:
disp(x3)
x3 =
0.2
class(x3)
ans =
double
step 3) but when I evaluate the function, it gives me a NaN. Like this:
res = funct(x3)
ans =
NaN
What I dont get is, if I plot the function, it exists at 0.2, and is equal to -0.4. If I do the following:
x3 = 0.2 % the class is still double, and I check it
class(x3)
ans =
double
then it works:
res = funct(x3)
res =
-0.4
Anybody has a hint of why it didnt work in the first place? I need it to work inside a huge loop, and I get these NaN which breaks the code. Any help is appreciated.

 Akzeptierte Antwort

Star Strider
Star Strider am 25 Mär. 2015

0 Stimmen

We need to see the code for ‘funct’.
However, NaN is either the result of one of the values in a calculation being NaN, or more often, a 0/0 or Inf/Inf division. Check for those in ‘funct’.

Weitere Antworten (1)

John D'Errico
John D'Errico am 25 Mär. 2015

0 Stimmen

Most probably, you THINK the original value is 0.2.
It looks like that after all. MATLAB displays it as such. But is it? Is it truly 0.2?
For example, it is trivial to give you a number that matlab will display as 0.2, but it is not so.
x3 = 0.2 + 1e-12
x3 =
0.2
Well, would you look at that! What a surprise.
x3 == 0.2
ans =
0
Next, it is equally trivial to write a function that will return a NaN for some values that are near 0.2, and a number that is not NaN for others. (Do I need to do this too?)
The point is, a NaN results from some computations, typically things that have an indeterminate result, like 0/0, inf/inf, inf-inf, or sin(inf). There are many ways it can happen, and I am sure I can come up with a few more quite easily.
You should check to see why it was created. So learn to use the debugger. Learn to use tools like dbstop, which can interrupt execution when a NaN is created.

1 Kommentar

Mortizo
Mortizo am 25 Mär. 2015
After the previous reply I found the problem to be exactly what you pointed out.
And before I asked the question, I obviously had to use the debugger to see what was happening, that's how I could tell the 0.2 and the -0.4, and check the other things, like variable type, etc.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 25 Mär. 2015

Kommentiert:

am 25 Mär. 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by