Stopping an Iteration when conditions have been met
4 次查看(过去 30 天)
显示 更早的评论
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')
0 个评论
回答(3 个)
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 个评论
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
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!