Save variables while using ode solver

11 次查看(过去 30 天)
[t,y]=ode45(@fun,tspan,yo);
function dy=fun(t,y)
dy=zeros(3,1);
constant1 = k1*y(3)
dy(1)= constant1;
dy(2)=f1(y(3),y(2))
dy(3)=f2(y(1),y(2))
end
I want to save the variable, constant1, each time the ode solver calls the function fun.
Is there a way to get the iteration count?
If yes, I can use
save_constant1(iter) = constant1.
Any suggestions?
  2 个评论
Steven Lord
Steven Lord 2019-10-24
What do you want to happen if the ODE solver evaluates your function for a particular time step but then rejects that step and evaluates your function at an earlier time (a smaller time step from the previous time?)
Deepa Maheshvare
Deepa Maheshvare 2019-10-25
Thanks a lot for the response. I suppose the step that is rejected will also be counted in the total number of iterations that the solver takes to solve the differential equations. So, I'd like to save the value of variable, constant1, for all iterations. Or, I could also create two variables, one that stores for all iterations and the other that skips the values computed at the steps that are rejected.

请先登录,再进行评论。

采纳的回答

Dinesh Yadav
Dinesh Yadav 2019-10-29
What you can try is at every iteration save the variables into a .mat file
save('odef.mat', 'constant1', '-append')
This will append the new values and keep your old values also.
Hope it helps.
  2 个评论
alesmaz
alesmaz 2019-11-1
Hi, I've tried your method in my code, where p is a vector of 4 parameters that I need to save at each ODE iteration in order to calculate their confidence intervals. I've put your string before the 'end' but my code overwrites always p without keeping the previous one.
Is there a way to save p at each ODE iteration without losing the one obtained in the previous iteration? Thank you.
function f=bernardode(p,t)
t=temposp;
options=odeset('AbsTol',1e-6,'RelTol',1e-6);
[T,Z]=ode45(@bernard2,t,z0,options);
function dz = bernard2(t,z)
dzdt=zeros(4,1);
dzdt(1)=-(p(3)*(1-qmin/z(1)))*(((Io/(sigma*L*z(2)))*(1-exp(-sigma*L*z(2))))/(p(4)+(Io/(sigma*L*z(2)))*(1-exp(-sigma*L*z(2)))))*z(1);
dzdt(2)=(p(3)*(1-qmin/z(1)))*(((Io/(sigma*L*z(2)))*(1-exp(-sigma*L*z(2))))/(p(4)+(Io/(sigma*L*z(2)))*(1-exp(-sigma*L*z(2)))))*z(2);
dzdt(3)=p(2)*z(4)+(p(3)*(1-qmin/z(1)))*(((Io/(sigma*L*z(2)))*(1-exp(-sigma*L*z(2))))/(p(4)+(Io/(sigma*L*z(2)))*(1-exp(-sigma*L*z(2)))))*(1-p(1)-z(3));
dzdt(4)=(p(1)-z(4))*(p(3)*(1-qmin/z(1)))*(((Io/(sigma*L*z(2)))*(1-exp(-sigma*L*z(2))))/(p(4)+(Io/(sigma*L*z(2)))*(1-exp(-sigma*L*z(2)))))-p(2)*z(4);
dz=dzdt;
end
f=Z;
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by