Nested While Loops won't restart

3 views (last 30 days)
Hi all!
I am having a very difficult time with my while loops. The idea of this code is supposed to guess a temperature (T), then calculate V using the inner while loop, proceed to calculate S, then go back up to the top and do it again until S is solved for.
The problem I am running into is that the inner while loop (solving for V) only runs once. Then, every time the outer while loop runs after that it just skips the inner while loop and send my temperature off into infinity. Please help! here is the code below.
while S_check>5
T=T+.5;
while pCheck>1
P = R*T/(V-b)-a/(sqrt(T)*V*(V+b));
p_out = 50; %bar
pCheck = abs(p_out-P)*100/p_out; %percent agreement
V=V-0.00001
end
rho=1/(V/0.04607);
S2=(5*a*log(1+rho*b)/(2*T^(3/2)*R)+log(rho)-log((1/rho)-b)+log(1/(1-rho*b)-a*rho/(T^1.5*R*(1+b*rho))))*R; %expression for entropy
S_check=abs(S2-S1)*100/S2; %percent agreement
end

Accepted Answer

Cris LaPierre
Cris LaPierre on 4 Dec 2020
Edited: Cris LaPierre on 4 Dec 2020
You likely need to reset the value of pCheck to something great than 1 before reaching the inner while loop. Otherwise, it will continue to use the value obtained at the end of the first pass, which is presumably <1, so the inner while loop is never run again.
You must have set it to something before the first pass or you would be getting an error message. Move that code/calculation to be inside the first while loop but before reaching the second one.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!