End a Calculation if a condition is satisfied.
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a calculation to perform:
Part A (Number of iterations are known)
ODE is solved using Runge Kutta 4 and I get an answer
Part B (I dont know the iterations to solve this)
ODE is solved using euler implicit
Condition (Part A-Part B <= 10e-5)
The program should end
Can you help me out with the code ?
[EDITED, Jan, moved from comment section:]
clear all;close all; clc;
format long;
u=1.5;
S=-33;
L=12/100;
N=11;
delx=L/(N-1);
K(1)=0.414;
y(1)=0;
C(1)=0.414;
x(1)=0;
%4th Order RK Method
for i=1:N-1
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
rk4=C(i+1);
N_euler=7839;
for j=1:7839 % i am not supposed to know that the iteration ends here,
it should be dynamic. (When N_euler = 7839, rk4-K(j+1)=10e-5)
%Euler Implicit
delxeuler=L/(N_euler-1);
y(j+1)=y(j)+delxeuler;
K(j+1)=(K(j)/delxeuler)*(1/((1/delxeuler)-(S/u)));
if abs(rk4-K(j+1))<0.00001
break
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')
legend('Euler Implicit: N=7389','Runge Kutta 4th Order: N=11');
0 commentaires
Réponse acceptée
Plus de réponses (1)
Rik
le 9 Fév 2017
The command you are looking for is 'while' instead of 'for'.
So replace the "for j=1:7839" in your code with "while abs(rk4-K(j+1))>0.00001" and you should be golden.
Note: with while loops you have to increment your counter yourself, otherwise your code will loop forever, so add a "j=j+1;" below your while
2 commentaires
Rik
le 9 Fév 2017
There are two options:
initialize K before the loop to a value start will result in starting the loop (e.g. K=10^6*rk4),
or you copy the content of the loop, so it runs once before it gets to the while
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!