フィルターのクリア

For loops vs. While loops

99 ビュー (過去 30 日間)
Joe
Joe 2013 年 3 月 12 日
コメント済み: Jos (10584) 2019 年 2 月 22 日
I know the two loops are used differently, although they could be used for the same purpose. However, how would you generally know which one to use, especially in cases where one over the other would be valid?

採用された回答

Jan
Jan 2013 年 3 月 12 日
編集済み: Jan 2013 年 3 月 12 日
The FOR loop is nicer and more compact, if the number of iterations is known before the loop is started. The WHILE loop is nicer, when the number of iterations is determined inside the loop.
Compare:
for k = 1:10
disp(k);
end
with:
k = 1;
while k <= 10
disp(k);
k = k + 1;
end
On the other hand:
a = 1e6;
while a > 1
a = a * rand;
end
with this (1e8 is an arbitrary large guess - a bad idea!):
a = 1e6;
for k = 1:1e8 % Ugly, although it is not created explicitly
a = a * rand;
if a <= 1
break;
end
end
There are some overlaps, e.g. running an iteration until a certain number of loops or a specific criterion is reached. Then usually WHILE is preferred with the convergence limit as test, because this reflects the main character of the loop, while the limitation of iterations is a fallback mechanism only.
  1 件のコメント
Jos (10584)
Jos (10584) 2019 年 2 月 22 日
The infinite for loop syntax is also nice to know:
for k=0:1e5:Inf,
if k > 1e6
break
end
disp(k)
end

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by