While-loop only iterates a single time
2 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
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.
More Answers (0)
See Also
Categories
Find more on Control System Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!