How do I avoid Infinite loop?

3 views (last 30 days)
Shashanka
Shashanka on 13 Jul 2014
Commented: Roger Stafford on 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 Comment
Azzi Abdelmalek
Azzi Abdelmalek on 13 Jul 2014
It's better to post your code as a text rather than an image

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 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 Comment
Image Analyst
Image Analyst on 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/

Sign in to comment.


Roger Stafford
Roger Stafford on 13 Jul 2014
Edited: Roger Stafford on 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 Comment
Roger Stafford
Roger Stafford on 13 Jul 2014
I have corrected the 'while' expression which was in error.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!