How to compare previous results in iteration?

5 ビュー (過去 30 日間)
ASHA PON
ASHA PON 2023 年 1 月 22 日
コメント済み: ASHA PON 2023 年 1 月 24 日
I have a program with for loop having 1to 500. I need to compare the output of previous and current iteration, if the outputs are matching the program has to stop. Otherwise the loop has to continue till the match is achieved.
For example:
for i=1 to 500
[Some mathematical calcultion]
output= 109;
end
Expected output:
iteration has to stop when output [i] = output [i-1]

回答 (1 件)

Torsten
Torsten 2023 年 1 月 22 日
編集済み: Torsten 2023 年 1 月 22 日
You should never check whether two variables are equal. Always check whether they are approximately equal:
difference = 1.0;
output_old = 0.0;
tolerance = 1e-6;
while difference > tolerance
[Some mathematical calculations]
output = ...;
difference = abs(output_old-output);
output_old = output;
end
  3 件のコメント
Torsten
Torsten 2023 年 1 月 22 日
編集済み: Torsten 2023 年 1 月 22 日
MATLAB does not have "integer" as data type. And I don't know how "output" is calculated in your code. So you should keep the code above as is. It will also work for integer values of "output".
ASHA PON
ASHA PON 2023 年 1 月 24 日
Thank you for the reply.

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by