MATLAB Answers

Can Ode 45 solve piecewise function in the iteration?

11 views (last 30 days)
Cola
Cola on 13 Sep 2021
Edited: Cola on 14 Sep 2021
In the iterative process of Ode45, the variable values change with time. The relationship between variable values corresponds to different system of differential equations. Whether it is possible to select the corresponding system of differential equations to continue the iterative calculation according to the relationship of the variable values.
For example:
The initial value is (x0, y0). At first time, x0>y0, so Ode45 selects the system (1) of differential equations for iterative calculation. Then the variable values x and y change with time. When x<=y, the system (2) of differential equations is selected to continue the iterative calculation. And so on.
Code:
t0=0;
tf=10;
x10=8;
x20=5;
x0=[x10,x20];
[t, x1] = ode45(@fun,[t0:tf], x0);
x2=[t,x1];
plot(x1(:, 1),x1(:, 2));
function f=fun(t,x)
f=zeros(2,1);
f(1)=-(x(1)-x(2))/x(1); % system(1),x(1)>x(2)
f(2)=(x(1)-x(2))/x(1)+1; % system(1),x(1)>x(2)
% f(1)=(x(2)-x(1))/x(2); % system(2),x(1)<=x(2)
% f(2)=1-(x(2)-x(1))/x(2); % system(2),x(1)<=x(2)
end
The initial value is x0=[x10, x20]=[8, 5], where x10 > x20, so Ode45 selects the system (1) of differential equations for iterative calculation. When t=3s, x(1)=7.6491, x(2)=8.3509, where x(1)<=x(2). Then I want the system (2) of differential equations is selected to continue the iterative calculation by using [7.6491, 8.3509] as a new initial value.
Thank you.
  3 Comments
Cola
Cola on 14 Sep 2021
I don't know if these codes are right.
Code1:
function f=fun(t,x)
f=zeros(2,1);
f(1)=(-(x(1)-x(2))/x(1))*(x(1)-x(2)>0)+((x(2)-x(1))/x(2))*(x(1)-x(2)<=0);
f(2)=((x(1)-x(2))/x(1)+1)*(x(1)-x(2)>0)+(1-(x(2)-x(1))/x(2))*(x(1)-x(2)<=0);
end
Code2:
function f=fun(t,x)
f=zeros(2,1);
if x(1)>x(2)
f(1)=-(x(1)-x(2))/x(1); % system(1),x(1)>x(2)
f(2)=(x(1)-x(2))/x(1)+1; % system(1),x(1)>x(2)
else
f(1)=(x(2)-x(1))/x(2); % system(2),x(1)<=x(2)
f(2)=1-(x(2)-x(1))/x(2); % system(2),x(1)<=x(2)
end
end

Sign in to comment.

Answers (1)

Bjorn Gustavsson
Bjorn Gustavsson on 13 Sep 2021
Your best approach is to use the events-handling procedure to interupt and restart the ode-integration whenever x and y passes the other. See the help and documentation for odeset and look at the code to ballode for an example of how to handle events.
In your case you might be able to proceed straight-away with the integration provided all f_1, f_2, g_1, g_2 and all their derivatives to some degree match, but I'm not even sure of that.
HTH

Community Treasure Hunt

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

Start Hunting!