当ODE45的解出现分歧时(无论为什么以及如何),将显示以下警告,解算器无法继续:
警告:t=8.190397e+01时发生故障。无法满足集成要求公差,而不将步长减小到最小值以下允许(2.273737e-13)。
我在矩阵上运行ode45(大量输入),所以我想自动找出哪个输入会出现上述条件(失败)。我的意思是,ode45返回的这个条件是否有其他符号可以自动写入数组?可以在if
语句中使用的东西:
if {some variable is returned/is equal to ...} then {the solver has failed}
以自动识别故障输入,而无需查找显示的警告。
您可以将warning
转换为error
,并且错误可以被try/catch
块捕获。
一个例子:
% Change this particular warning into an error
warnId = 'MATLAB:ode45:IntegrationTolNotMet';
warnstate = warning('error', warnId);
% That can be caught with try/catch
try
% Quick-failing integration, suggested by horchler
[t,y] = ode45(@(t,y)[y(1)^2;y(2)],[0 1],[1;1]);
catch ME
% Check if we indeed failed on meeting the tolerances
if strcmp(ME.identifier, warnId)
% DO YOUR STUFF HERE
else
% Something else has gone wrong: just re-throw the error
throw(ME);
end
end
% Don't forget to reset the warning status
warning(warnstate);
您可以通过lastwarn
命令获得任何警告的warnId
。有关错误,请参阅lasterr
。
另一种方法是只检查ode45能够运行多少时间。例如,如果运行
[x,t] = ode45(@some_ode,[t0,tf],x0);
执行完这一行之后,只需检查t(end)的值即可。如果t(end)==tf,则ode45完成其工作,否则出现故障