How to end an indefinite loop?
Show older comments
My goal;
- Guess values of T
- Use T to calculate L
- Find largest L element
- Update the T element correlating to the largest L element. Keep other T's unchanged.
- Use updated T array to find L again.
- Repeat until largest L element is less than 0.1.
Basically, I keep updating T until all L elements are below 0.1. Currently, it never stops and doesn't give the right T array, which is supposed to be [326; 307; 301; 301]
Hope this makes sense. All suggestions welcome
%Convergence Program
%start
clearvars; clc;
%Guess
T = zeros(4,1);
T(1) = input("T1? ");
T(2) = input("T2? ");
T(3) = input("T3? ");
T(4) = input("T4? ");
%Leftovers
L = zeros(4,1);
L(1) = abs(1000+T(2)-4*T(1));
L(2) = abs(600+T(1)+T(3)-4*T(2));
L(3) = abs(600+T(2)+T(4)-4*T(3));
L(4) = abs(600+2*T(3)-4*T(4));
%Largest
[rem, pos] = max(L);
%Loop
while rem > 0.1
if(pos==1)
T(1) = 0.25*(1000+T(2));
L(2) = abs(600+T(1)+T(3)-4*T(2));
L(3) = abs(600+T(2)+T(4)-4*T(3));
L(4) = abs(600+2*T(3)-4*T(4));
[rem, pos] = max(L);
elseif(pos==2)
T(2) = 0.25*(600+T(1)+T(3));
L(1) = abs(1000+T(2)-4*T(1));
L(3) = abs(600+T(2)+T(4)-4*T(3));
L(4) = abs(600+2*T(3)-4*T(4));
[rem, pos] = max(L);
elseif(pos==3)
T(3) = 0.25*(600+T(2)+T(4));
L(1) = abs(1000+T(2)-4*T(1));
L(2) = abs(600+T(1)+T(3)-4*T(2));
L(4) = abs(600+2*T(3)-4*T(4));
[rem, pos] = max(L);
elseif(pos==4)
T(4) = 0.25*(600+2*T(3));
L(1) = abs(1000+T(2)-4*T(1));
L(2) = abs(600+T(1)+T(3)-4*T(2));
L(3) = abs(600+T(2)+T(4)-4*T(3));
[rem, pos] = max(L);
elseif rem < 0.1
break
end
end
Accepted Answer
More Answers (1)
Image Analyst
on 25 Feb 2022
You're making the same mistake that nearly everyone who writes a while loop makes: you are not using a failsafe to prevent an infinite loop. I tell people this several times per week. So if your code never generates a condition to exit (because of a logic error like you have), then the loop will continue forever. The solution is to use a loop counter and maximum number of iterations that you expect as a failsafe:
loopCounter = 1;
maxIterations = 1000000; % Way more than you ever expect to be done.
while (remainder > 0.1) && (loopCounter <= maxIterations)
% Code to set remainder....
% Now at the end of the loop, increment the loop counter to make sure we don't go infinite
loopCounter = loopCounter + 1;
end
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!