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

517 ビュー (過去 30 日間)
Zeyad Elsayed
Zeyad Elsayed 2019 年 8 月 14 日
コメント済み: Guillaume 2019 年 8 月 14 日
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
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
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
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 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by