How to compare previous results in iteration?

조회 수: 4 (최근 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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by