Access previous iteration in while loop to derive stopping criterion for differential equation correction-prediction method

조회 수: 8(최근 30일)
KostasK 2020년 1월 13일
답변: Bob Thompson 2020년 1월 13일
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.
% 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
y_corr = y_pred ;
yEUL(i) = y_corr ;
% Plot
plot(tODE, yODE, '-ob', tEUL, yEUL, '-or')
legend('ODE45', 'EULER', 'Location', 'West')
grid on
Thanks for your help in advance,

채택된 답변

Bob Thompson
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
y_corr = y_pred(i);
% Variable method
while true
i = i + 1;
y_pred = ...
if abs(y_pred-y_corr) < e
y_prev = y_corr;
y_corr = y_pred;

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by