I have a problem using a while loop. My main objective is to simulate a Fanno flow problem for a case where the length of the tube is longer than required. This means we have to change the Mach number in the middle. My code is the following.
clc
clear all
close all
P1=1;
T1=273;
Cf=0.005;
Dh=0.15;
G=1.4;
M1=3.0;
Lxstar=0;
M2=1;
Lx=0;
My=0;
Lystar=0;
tol=.001;
L = 6.0;
error=0;
fp = ((1-M1^2)/(G*M1^2))+((G+1)/(2*G))*log(((G+1)*M1^2)/(2*(1+(M1^2*(G-1)/(2)))))
Lstar=(fp*Dh)./(4*Cf)
while Lstar<L
Mx=(M1+M2)./2
fp1=((1-Mx^2)/(G*Mx^2))+((G+1)/(2*G))*log(((G+1)*Mx^2)/(2*(1+(Mx^2*(G-1)/(2)))))
Lxstar= (fp1*Dh)./(4*Cf)
Lx= Lstar-Lxstar
My=((sqrt((2+(G-1)*Mx.^2)/(2*G*Mx.^2-(G-1)))));
fp2=((1-My^2)/(G*My^2))+((G+1)/(2*G))*log(((G+1)*My^2)/(2*(1+(My^2*(G-1)/(2)))))
Lystar=(fp2*Dh)./(4*Cf)
error= Lx+Lystar-L
if error<=tol
break
else
Diff=Lx+Lystar
if Diff<L
Mx=Mx+.01
else
Mx=Mx-.01
end
end
end
When I run it goes smoothly - it does everything I want but once it changes the Mx it runs again with the Mx=M1+M2/2 instead of the corrected Mx = Mx+.01 or Mx= Mx-.01
Mx = (M1+M2)./2is inside your while-loop. So it gets redefined in the beginning of each loop.