While-loop only iterates a single time

2 views (last 30 days)
Thom21
Thom21 on 25 Sep 2018
Reopened: Walter Roberson on 22 Dec 2018
I'm trying to find a value for h by first guessing a value (0.00001<h<0.003) and then using a while loop to find the correct value.
W = 0.3; %Channel width (m).
S = 0.006; %Channel slope (m/m).
ks = 0.0013; %Nikuradse roughness length (m).
Q = 1e-3; %Water flow (m^3/s)
h = 0.0004; %Initial water depth to start while-loop.
htemp = .9*h; %Controlling value to determine if we are getting a better value for h.
while (h-htemp)>(1e-6)
R = (W * h) / (W + 2*h); %Calculate hydraulic radius.
C = 18*log10((12*R)/ks); %Calculate grain-related Chezy number.
u = C*(h*S)^(.5); %Calculate flow velocity.
htemp = Q / (W*u); %Calculate depth of the water.
h = (h+htemp)/2
end
However, I only seem to get the while loop to do a single iteration, even though the end result does not satisfy the initial condition. How could I get this to work?

Accepted Answer

Image Analyst
Image Analyst on 25 Sep 2018
Edited: Image Analyst on 25 Sep 2018
Simple debugging would have let you know. But to be more explicit, try this where I added fprintf's to your code:
W = 0.3; %Channel width (m).
S = 0.006; %Channel slope (m/m).
ks = 0.0013; %Nikuradse roughness length (m).
Q = 1e-3; %Water flow (m^3/s)
h = 0.0004; %Initial water depth to start while-loop.
htemp = .9*h; %Controlling value to determine if we are getting a better value for h.
while (h-htemp)>(1e-6)
R = (W * h) / (W + 2*h); %Calculate hydraulic radius.
C = 18*log10((12*R)/ks); %Calculate grain-related Chezy number.
u = C*(h*S)^(.5); %Calculate flow velocity.
htemp = Q / (W*u); %Calculate depth of the water.
h = (h+htemp)/2;
fprintf('h = %f\n(h-htemp) = %f\n', h, (h-htemp));
if (h-htemp)>(1e-6)
fprintf('It is greater than 1e-6 so the loop will iterate again.\n');
else
fprintf('It is NOT greater than 1e-6 so the loop will not iterate again.\n');
end
end
You will see
h = 0.105771
(h-htemp) = -0.105371
It is NOT greater than 1e-6 so the loop will not iterate again.
  1 Comment
Thom21
Thom21 on 25 Sep 2018
A friend also kindly pointed me to this obvious flaw in my code. I changed it to abs(h-htemp), which consistently gives me the same answer :)

Sign in to comment.

More Answers (0)

Categories

Find more on Control System Toolbox 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!