Stopping an Iteration when conditions have been met

16 visualizaciones (últimos 30 días)
DIP
DIP el 5 de Feb. de 2017
Comentada: Walter Roberson el 5 de Feb. de 2017
Hi guys, im trying to create a loop where I have to compare the euler implicit and RK4 method to compare the accuracy. The implicit method is should stop at 92 iterations to meet the condition where the absolute difference of the solution between the two methods is less than 10e-5.
Thanks !
% Euler’s Implicit Method and RK4
clear;close;clc;
u=1.5;
S=-33;
L=12/100;
N=10000;
delx=L/(N-1);
K(1)=0.414;
y(1)=0;
C(1)=0.414;
x(1)=0;
A=10;
delx=L/(A-1);
for i=1:inf % Loop for Implicit
%Euler Implicit
y(i+1)=y(i)+delx;
syms a;
eqn= a ==(K(i)+delx*(a*S/u));
K(i+1) = double(solve(eqn,a));
for i=1:A %loop for RK4
%4th Order RK Method
x(i+1)=x(i)+delx;
k1 = delx*(S/u*C(i));
k2 = delx*(S/u*C(i)+S/u*k1/2);
k3 = delx*(S/u*C(i)+S/u*k2/2);
k4 = delx*(S/u*C(i)+S/u*k3);
C(i+1) = C(i) + (1/6)*(k1+2*k2+2*k3+k4);
end
if abs((C(i+1)-K(i+1)))==0.01
break
else
return
end
end
plot(y,K,'-.+','color','g')
title('Concentration of CO vs. Distance');
xlabel('Axial(x) Direction [m]');
ylabel('Concentration of CO[mol/m3]');
hold on
plot(x,C,'-o','color','r')

Respuestas (3)

the cyclist
the cyclist el 5 de Feb. de 2017
You are checking for exact equality. Try
if abs((C(i+1)-K(i+1)))<=0.01
instead.

DIP
DIP el 5 de Feb. de 2017
Can anyone suggest to me in general how you dynamically change the iterations ? I want the iteration of the euler implicit to end at 92 iterations.

Walter Roberson
Walter Roberson el 5 de Feb. de 2017
You have
for i=1:inf % Loop for Implicit
and within that you have
for i=1:A %loop for RK4
which is using the same variable, i . MATLAB will be able to figure out how to loop properly (it stores the current iteration value internally), but inside that second loop your code is going to be very confused about what i means.
If you want to break at 92 iterations, then change the "inf" to 92.
Also, get rid of that "return"
  2 comentarios
DIP
DIP el 5 de Feb. de 2017
i want the code to be dynamic , the iteration should end at 92 without me limiting the code to 92 iterations.
Walter Roberson
Walter Roberson el 5 de Feb. de 2017
for iter=1:inf % Loop for Implicit
%Euler Implicit
y(iter+1)=y(iter)+delx;
syms a;
eqn= a ==(K(iter)+delx*(a*S/u));
K(iter+1) = double(solve(eqn,a));
for i=1:A %loop for RK4
%4th Order RK Method
x(i+1)=x(i)+delx;
k1 = delx*(S/u*C(i));
k2 = delx*(S/u*C(i)+S/u*k1/2);
k3 = delx*(S/u*C(i)+S/u*k2/2);
k4 = delx*(S/u*C(i)+S/u*k3);
C(i+1) = C(i) + (1/6)*(k1+2*k2+2*k3+k4);
end
if abs((C(A+1)-K(iter+1))) <= 0.01
break
end
end

Iniciar sesión para comentar.

Categorías

Más información sobre Mathematics en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by