Evaluating an ODE until you reached a certain distance using a while loop: Train/distance problem
Show older comments
Hello, I was wondering how you'd evaluate a ode until it reaches a wanted distance. For me I'm trying to code it so that it run until R is equal to the distance, which is 3. Any tips on were I'm going wrong? Thanks
% code
function tr()
gr = 4.66; r = 1; D = 2;
options = odeset('events', @location);
[t,R] = ode45(@coupled,[0,3],[r;3],3);
V=R(1,2);
plot(t,R(:,1),'o',t,R(:,2),'o');
shg
%end
[T1,Y1,te,ye,ie]=ode45(@coupled,[1:1:50], [1;3],options);
disp(te);
function [lookfor,stop,direction]=location(t,y)
lookfor=y(2)-3; % Stop at 3
stop=1;
direction=0;
end
function dYdt = coupled(w,Y)
dYdt = zeros(1,2);
dYdt = [Y(1);-(pi^2/6)^2*cos(pi*w)^2-gr*sin((pi/8)*cos(pi*w))];
end
end
end
5 Comments
Are Mjaavatten
on 28 Apr 2018
It is not clear to me what you are trying to do. Do you want to:
1) Solve the ODE on the interval [0,3] and vary the initial value of t until R(x=3) = 3?
2) Solve for an interval [0,xmax] so that R(x=xmax) = 3?
Or something else entirely?
panacean
on 28 Apr 2018
Are Mjaavatten
on 29 Apr 2018
I am still confused. Is x and R both distances? Could you post your coupled function and explain the meaning of the variables x, t and R?
Are Mjaavatten
on 3 May 2018
I would still like a better explanation of what you are trying to do. If I interpret your function coupled(w,Y) correctly, you try to so solve the coupled differential equations

What is the independent variable w? Time? What are the two components of Y. (Is Y(1) = R?).
Note that your equations are not coupled at all, but two independent differential equations. Note also that the variable gr must be given a value.
The analytical solution is:

I am not sure that this is what you want. Please give a better description of the original problem.
Accepted Answer
More Answers (1)
Torsten
on 30 Apr 2018
0 votes
Use the "Event" option of ode45 to locate the t-value at which R=3.
Best wishes
Torsten.
Categories
Find more on Ordinary Differential Equations 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!