# How to repeat loop until condition is met? While or For Loop?

448 views (last 30 days)
Zeyad Elsayed on 14 Aug 2019
Commented: Guillaume on 14 Aug 2019
Hello everyone,
I wanted to create a loop until a certain condition is met, for example lets say I have constant x, that is included in equations A and B. Error is A-B. I want the x to keep changing until Error < 1E-3. How can I do this?
syms x
A = x + 1.5;
B = x^2 + 1;
Error = A-B;
I dont even know where to start, should I be using a for loop or a while loop?
##### 2 CommentsShowHide 1 older comment
Guillaume on 14 Aug 2019
@Kalyan, you've got your while condition reversed. It should be
while Error > 1e-3
Note that using Error has a variable is not a terribly good idea. It's too close to the error function.
You can always interchange for and while loops, however for loops are better suited for loops where you know in advance how many times you're going to loop, and while loops are better suited for loops where you don't know how many loops you have (because you end on a condition), so:
%know how many iterations:
for i = 1:numiter
%do something numiter times
end
%don't know when it ends
while ~condition
%do something until condition is true
end
But as I said, you can always convert one to the other:
%while equivalent of the for loop above:
i = 1;
while i <= numiter
%o something numiter times
i = i+1;
end
%for equivalent of the while loop above:
for i = 1:Inf
if condition, break, end;
%do something until condition is true
end

Alex Mcaulley on 14 Aug 2019
Edited: Alex Mcaulley on 14 Aug 2019
Something like this would be a good solution:
x = %Initialization
A = x + 1.5;
B = x^2 + 1;
Error = A-B;
iter = 1;
while Error > 1e-3 && iter < maxIter %To avoid infinite loops
x = %Updating x
A = x + 1.5;
B = x^2 + 1;
Error = A-B;
iter = iter + 1;
end
if iter == maxIter
warning('Max Iterations reached')
end

R2017a

### Community Treasure Hunt

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

Start Hunting!

Translated by