Clear Filters
Clear Filters

Way to decrease the step size in the while loop.

7 views (last 30 days)
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 Comments
Jan
Jan on 13 Mar 2023
Edited: Jan on 13 Mar 2023
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 on 13 Mar 2023
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.

Sign in to comment.

Answers (1)

Dinesh
Dinesh on 6 Apr 2023
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.

Categories

Find more on Loops and Conditional Statements 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!