I keep getting NaN
Show older comments
For some reason my T values keeps giving me NaN when putting greater values. I dont understand why the error occurs.
clc, clear all
T=0
summa=0;
x=60;%distance x=60 whole distance
s=0;
n=1%amount of steps (change this depending on the x)
route=input('1 or 2:')
%check approx anwser
fun= @(x) 1./(velocity(x,route));
check=60.*integral(fun,0,x) %in min
T=60.*time_to_destination(x,route,n)
while abs(check-T)>=1 %+-0.5 will give a span of 1
T=60.*time_to_destination(x,route,n); %in min
n=n+1;
end
svar=n %antal steg
t=T %integral approx värde (in min)
function T= time_to_destination(x,route,n)
s=0; %start vilkkor
summa=0;
h=x./n;
for i=0:h:x;
v=1./(velocity(s,route));
v2=1./(velocity((s+h),route));
summa=(h./2).*(v+v2)+summa; %trapets def
s=s+h;
end
T=summa;
end
6 Comments
John D'Errico
on 15 Sep 2020
How can someone help you, if you do not provide sufficient information to do so? For example, what is velocity? (Don't tell me rate of change of distance traveled.) At least, in terms of matlab, what is velocity? It is not defined, so it must be a function that you have kept secret.
A NaN results when one of several indeterminate things happens. For example 0/0, inf/inf, inf-inf, etc. But we have no way to track that down, since we are not you. However, you can learn to use the debugger, which is what someone else would probably do anyway.
Adam Danz
on 15 Sep 2020
NaNs spread like wildfire. Somewhere in your script a NaN is produced and it's likely affecting other variables, too. As John mentioned, we have no change of troubleshooting without being able to run your script.
John D'Errico
on 15 Sep 2020
I'd suggest this command:
dbstop if infnan
Then look at what you have. Where did the inf or NaN arise? What caused it? Look carefully at your code. See that infs can often then turn into NaNs. For example
>> inf/inf
ans =
NaN
>> inf - inf
ans =
NaN
So infs can be precursors to NaNs. And once NaNs happen, they just breed like wire coat hangars in back of your closet.
Daniel Hodgson
on 15 Sep 2020
Edited: Adam Danz
on 15 Sep 2020
Adam Danz
on 15 Sep 2020
That's helpful, Daniel Hodgson, but we need to be able to reproduce the NaN values on our end before we can trace back to their origins.
If there are any NaN values in the "v" output, please attach the two files.
If there aren't any NaN values in "v" you could produce v, save it to a mat file, and attach that mat file (or share the two files).
To determine if an array has any NaNs,
any(isnan(v),'all')
Daniel Hodgson
on 15 Sep 2020
Answers (0)
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!