Way to decrease the step size in the while loop.

7 次查看(过去 30 天)
Hello,
belows are my code that find the 'Q' value which 'S' meets the tolerance of 0.1 % relative error.
I hava some issue when the step size (which is 1 for now) is too large, it repeats back and forth sometimes.
for example, Q is 101, 100, 101, 100, 101 ... without converge.
In that case, I want to decrease the step size 1 to 0.5 (for example). But I have no idea how to do that.
Please give me an insight !
while abs((S(801,1)-1000)/1000)>0.001
fprintf(' Q finding \n')
if S(801,1) > 1000 && abs((S(801,1)-1000)/1000)>0.001
Q = Q - 1;
Calcilation code
elseif S(801,1) < 1000 && abs((S(801,1)-1000)/1000)>0.001
Q = Q + 1;
Calcilation code
elseif abs((shoreline(801,1)-1000)/1000) < 0.001
end
end
  2 个评论
Jan
Jan 2023-3-13
编辑:Jan 2023-3-13
Please use the tools for formatting code in the forum. Thanks.
What happens for S(801,1) == 1000 and abs((S(801,1)-1000)/1000) == 0.001? You get an infinite loop. Another strange formulation:
s = S(801, 1); % simpler code
s < 1000 && abs((s-1000)/1000)>0.001
% is equivalent to:
s < 1000 && abs((s-1000)) > 1
% is equivalent to:
s < 1000 && (s > 1001 || s < 999)
% is equivalent to:
s < 999
The code can and should be simplified.
A fixed increment cannot produce a convergence. Use Newton method instead.
Cameron
Cameron 2023-3-13
This code looks incomplete. How are you getting out of the loop? What is the variable "shoreline"? What is Q? You're not updating S(801,1) every iteration so if you get into the while loop you'll never get out.

请先登录,再进行评论。

回答(1 个)

Dinesh
Dinesh 2023-4-6
Hi Minsik.
You can introduce a variable called "stepSize" within the for loop which equals to 1 or 0.5.
At the beginning of every iteration of the while loop, you can check if the values are not converging. If they are not, then you can change the "stepSize" accordingly, in this case you can change it to 0.5.
if <condition>
stepSize = 0.5;
end
Then, you can increment/decrement the value of 'Q' by the "stepSize" variable in the corresponding conditional statements.
Q = Q - stepSize; // or Q = Q + stepSize;
But as I can see the loop itself, it doesn't look correct to be because it would just run infinitely since the value of S(801,1) remains the same. You might have to update the value of S(801,1) every time the loop iterates to prevent this problem.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by