While-loop only iterates a single time

6 Ansichten (letzte 30 Tage)
Thom21
Thom21 am 25 Sep. 2018
Erneut geöffnet: Walter Roberson am 22 Dez. 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?

Akzeptierte Antwort

Image Analyst
Image Analyst am 25 Sep. 2018
Bearbeitet: Image Analyst am 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 Kommentar
Thom21
Thom21 am 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 :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Control System Toolbox finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by