フィルターのクリア

Creating a for loop based on a condition

2 ビュー (過去 30 日間)
Lorenzo Merlino
Lorenzo Merlino 2023 年 12 月 25 日
移動済み: Dyuman Joshi 2023 年 12 月 26 日
Hello everyone, I need to create a for loop which iterates until it is met a specific condition, which in my case is the output being equal to a certain value. I know a while loop would suffice, though I would require a for-loop in order to use the index of the iteration to store the output of said iteration into an array, so that I can have a full accountability of all the results the loop gets.
  1 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 12 月 25 日
移動済み: Dyuman Joshi 2023 年 12 月 26 日
Use break or return.

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

採用された回答

Walter Roberson
Walter Roberson 2023 年 12 月 25 日
for K = 1 : inf
do some calculation
stored_results(K) = the_output
if the_output == the_certain_value
break;
end
end
or
K = 0;
while true
do some calculations
K = K + 1;
stored_results(K) = the_output;
if the_output == the_certain_value
break;
end
end
However... remember that the == operator is looking for bit-for-bit equality, and it is possible that you cannot get bit-for-bit equality due to round-off and finite precision . You are typically better off checking to see whether the output is "close enough" to the desired value, such as with ismembertol()

その他の回答 (1 件)

Torsten
Torsten 2023 年 12 月 25 日
編集済み: Torsten 2023 年 12 月 25 日
i = 0;
tolerance = 1e-4;
imax = 100;
output = 1;
value = ...;
while abs(output-value) > tolerance && i < imax
i = i + 1;
... % compute something
output = ...;
OutputArray(i) = output;
end
plot(1:i,OutputArray)

カテゴリ

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