While-loop only iterates a single time

조회 수: 2 (최근 30일)
Thom21
Thom21 2018년 9월 25일
다시 열림: Walter Roberson 2018년 12월 22일
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?

채택된 답변

Image Analyst
Image Analyst 2018년 9월 25일
편집: Image Analyst 2018년 9월 25일
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
Thom21
Thom21 2018년 9월 25일
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 :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Control System Toolbox에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by