问题描述
我尝试保存/查看在ode45微分方程求解过程中通过if循环更改的变量m。
%some parameter setting above
myfun=fprintf('m',num2str(m))
options = odeset('NonNegative',[1:3],'RelTol',1e-5,'AbsTol',1e-8,'OutputFcn',@myfun);
[t,x] = ode45('myfunction',tspan,x0,options); %calculation
if循环位于所有其他方程式之前的方程式文件中:
if x(1)>=threshold
m=1 ;
return
else
m=0 ;
end
我已经看过ode45的OutputFcn选项的matlab描述,并且已经阅读 https://de.mathworks.com/help/deeplearning/ug/customize-output-during-deep-learning-training.html 没有正确理解它。我也愿意接受其他解决方案来“查看”在ode计算中具有哪个值。
解决方法
创建一个单独的文件,并使用以下代码将此文件命名为myOutputFcn.m
function status = myOutputFcn(t,y,flag,threshold)
switch(flag)
case 'init' % code to run before integration
;
case '' % code to run after each integration step
% act on state
if y(1)>=threshold
m = 1;
else
m = 0;
end
% print m
fprintf('% 4.3f\t%i,t,m\n',m);
case 'done' % code to run when integation is finished
;
end
status = 0; % need to set status,otherwise integration will halt
end
然后使用正确的阈值在每次迭代中调用此输出函数,您将必须执行以下操作
threshold = 10; % idk,your threshold
options = odeset('NonNegative',[1:3],'RelTol',1e-5,'AbsTol',1e-8,'OutputFcn',@(t,flag) myOutputFcn(t,threshold));
[t,x] = ode45('myfunction',tspan,x0,options); %calculation