How to repeat loop until condition is met? While or For Loop?
347 次查看(过去 30 天)
显示 更早的评论
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 个评论
KALYAN ACHARJYA
2019-8-14
编辑:KALYAN ACHARJYA
2019-8-14
"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
2019-8-14
@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
采纳的回答
Alex Mcaulley
2019-8-14
编辑:Alex Mcaulley
2019-8-14
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!