Anonymous function returning NaN
Mostrar comentarios más antiguos
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.
Respuesta aceptada
Más respuestas (1)
John D'Errico
el 25 de Mzo. de 2015
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 comentario
Mortizo
el 25 de Mzo. de 2015
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!