Access previous iteration in while loop to derive stopping criterion for differential equation correction-prediction method
2 次查看(过去 30 天)
显示 更早的评论
Hi all,
I have been trying to write a prediction-correction method for matrix differential equations, however I have been unsuccessful, as I do not know how to access the previous iteration in the while loop in order to derive the stopping criterion. In specific, my method is the following:
Lets assume:
Then we make an initial guess via Euler:
Next we improve the intial guess in an iterative process which stops if , where e is a user defined tolerance:
Hence, the above implies that the previous step has to be accessed in a while loop such that if the condition for e is achieved, then the iteration stops. I have attempted to use the answer from this question, however I must be doing something wrong as there is no improvement in the answer as I change the tolerance:
-----
EDIT: The actual equation that I have to solve is way more complex than the differential equation in the code below. I just used the differential equation below in order to make it easier for myself to identify a solution to my problem.
-----
clear
clc
% Inputs
tmax = 5 ; % Max solution time
y0 = 0 ; % Initial conditions
Dt = 0.1 ; % Time step (for Euler)
e = 1e-3 ; % Tolerance (for Euler)
odefun = @(t, y) 2*t ; % Function to be integrated
% Solution
% ODE45
[tODE, yODE] = ode45(odefun, [0 tmax], y0) ;
% Euler
tEUL = transpose(0:Dt:tmax) ;
yEUL = [y0 ; zeros(length(tEUL)-1, 1)] ;
for i = 2:length(tEUL)
yEUL(i) = yEUL(i-1) + Dt * odefun(Dt*i, yEUL(i-1)) ;
y_pred = yEUL(i) ;
y_corr = Inf ;
while true
y_pred = yEUL(i-1) + Dt / 2 * (odefun(Dt*i, yEUL(i-1)) + odefun(Dt*(i+1), y_pred)) ;
if abs(y_pred - y_corr) < e
break
end
y_corr = y_pred ;
end
yEUL(i) = y_corr ;
end
% Plot
figure
plot(tODE, yODE, '-ob', tEUL, yEUL, '-or')
legend('ODE45', 'EULER', 'Location', 'West')
grid on
Thanks for your help in advance,
KMT.
0 个评论
采纳的回答
Bob Thompson
2020-1-13
In MATLAB, you cannot access the previous iteration of a loop directly. If you want to utilize that information you need to either index your results, or record the previous iteration as a separate variable.
% Index method
i = 0;
while true
i = i + 1;
y_pred(i) = ...
if abs(y_pred(i)-y_corr) < e
break
end
y_corr = y_pred(i);
end
% Variable method
while true
i = i + 1;
y_pred = ...
if abs(y_pred-y_corr) < e
break
end
y_prev = y_corr;
y_corr = y_pred;
end
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!