How to repeat loop until condition is met? While or For Loop?
249 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Zeyad Elsayed
il 14 Ago 2019
Commentato: Guillaume
il 14 Ago 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?
Thanks in advance!
2 Commenti
KALYAN ACHARJYA
il 14 Ago 2019
Modificato: KALYAN ACHARJYA
il 14 Ago 2019
"for example lets say I have constant x"
If you have constant x, how would you expect A and/or B to be change for change the Error during iterations?
Please note If x is constant, then A and B will remain same.
*If x is varrying, then it is easy
Error=0;
while Error < 1E-3.
A = x + 1.5;
B = x^2 + 1;
Error = A-B;
end
Pease note that Error must be decresing, so that loop will terminate
Guillaume
il 14 Ago 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.
@Zeyad,
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
Risposta accettata
Alex Mcaulley
il 14 Ago 2019
Modificato: Alex Mcaulley
il 14 Ago 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
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!