Access previous iteration in while loop to derive stopping criterion for differential equation correction-prediction method
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
KostasK
le 13 Jan 2020
Réponse apportée : Bob Thompson
le 13 Jan 2020
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 commentaires
Réponse acceptée
Bob Thompson
le 13 Jan 2020
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!