End a Calculation if a condition is satisfied.

조회 수: 2 (최근 30일)
DIP
DIP 2017년 2월 9일
답변: DIP 2017년 2월 20일
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');

채택된 답변

DIP
DIP 2017년 2월 20일
while abs(rk4-imp)>=0.00001
N_euler = N_euler+1;
delxeuler=L/(N_euler-1);
for j=1:N_euler-1
%Euler Implicit
y(j+1)=y(j)+delxeuler;
K(j+1)=(K(j)/delxeuler)*(1/((1/delxeuler)-(S/u)));
imp=K(j+1);
err=rk4-imp;
end
end

추가 답변 (1개)

Rik
Rik 2017년 2월 9일
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
DIP
DIP 2017년 2월 9일
but K(j+1) is not defined. and will throw an error. Also, how do I define the stepsize delxeuler ?
Rik
Rik 2017년 2월 9일
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

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by