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.

 채택된 답변

Star Strider
Star Strider 2015년 3월 25일

0 개 추천

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’.

추가 답변 (1개)

John D'Errico
John D'Errico 2015년 3월 25일

0 개 추천

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

Mortizo
Mortizo 2015년 3월 25일
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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2015년 3월 25일

댓글:

2015년 3월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by