Stopping an Iteration when conditions have been met

조회 수: 2 (최근 30일)
DIP
DIP 2017년 2월 5일
댓글: Walter Roberson 2017년 2월 5일
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')

답변 (3개)

the cyclist
the cyclist 2017년 2월 5일
You are checking for exact equality. Try
if abs((C(i+1)-K(i+1)))<=0.01
instead.

DIP
DIP 2017년 2월 5일
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 2017년 2월 5일
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
DIP
DIP 2017년 2월 5일
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 2017년 2월 5일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by