Hi I have a problem using a while loop with matlab

58 Views Asked by At

I have a problem using a while loop. My main objective is to simulate a fanno flow problem when for a case where the length of the tube is longer than require. 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

1

There are 1 best solutions below

6
On BEST ANSWER

Pull the assignment of Mx out of the loop. It is being reassigned every time.

Mx=(M1+M2)./2
while Lstar<L



    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