Filter löschen
Filter löschen

How do I avoid Infinite loop?

2 Ansichten (letzte 30 Tage)
Shashanka
Shashanka am 13 Jul. 2014
Kommentiert: Roger Stafford am 13 Jul. 2014
I am facing an 'Infinite Loop' condition in the attached piece of code. The 'AxIF' is to be updated with each iteration with the latest value of 'AxIFN'. Finally giving a value of 'AxIFN' which is less than '0.4'. After which the loop is exited.
  1 Kommentar
Azzi Abdelmalek
Azzi Abdelmalek am 13 Jul. 2014
It's better to post your code as a text rather than an image

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Image Analyst
Image Analyst am 13 Jul. 2014
AxIF will never equal 0.4 to the 15th decimal place. To find out why, see the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F. Try checking within a tolerance like the FAQ suggests:
if abs(AxIF-0.4) < 0.00001 % Or whatever tolerance you want.
  1 Kommentar
Image Analyst
Image Analyst am 13 Jul. 2014
Or maybe you wanted <= instead of ==.
if AxIF <= 0.4
break;
end
If it still doesn't exit the loop, step through it with the debugger to figure out why. http://blogs.mathworks.com/videos/2012/07/03/debugging-in-matlab/

Melden Sie sich an, um zu kommentieren.


Roger Stafford
Roger Stafford am 13 Jul. 2014
Bearbeitet: Roger Stafford am 13 Jul. 2014
Your use of the while loop is inappropriate for the problem you are dealing with. You stated, "The 'AxIF' is to be updated with each iteration with the latest value of 'AxIFN'. Finally giving a value of 'AxIFN' which is less than '0.4'. After which the loop is exited." This, along with the test "AxIF < 0.4", shows a misunderstanding of how the 'while' command functions. You are apparently waiting for the sequence of AxIFN values to converge to a limit which you hope will be less than 0.4 . It is not nearly that smart. As you have learned to your sorrow, the while loop will never stop the way you have written the code.
To test that convergence has been achieved you need to test that successive values of AxIF are sufficiently close to one another that the sequence has essentially converged. You can do that according to this outline:
AxIF = 0.3543;
AxIFN = inf; % Set this to ensure initial entry into the while loop
while abs(AxIF-AxIFH) >= tol (<-- Corrected))
AxIFN = AxIF;
Calculate the next value of AxIF from AxIFN
....
(Don't do AxIFN = AxIF down here)
end
where 'tol' is some positive quantity so small that it indicates essentially successful convergence - that is, near equality of two successive values.
  1 Kommentar
Roger Stafford
Roger Stafford am 13 Jul. 2014
I have corrected the 'while' expression which was in error.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by