Can Ode 45 solve piecewise function in the iteration?
11 次查看(过去 30 天)
显示 更早的评论
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/737509/image.png)
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/737514/image.png)
Thank you.
3 个评论
回答(1 个)
Bjorn Gustavsson
2021-9-13
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Numerical Integration and Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!