Borrar filtros
Borrar filtros

How do I avoid Infinite loop?

3 visualizaciones (últimos 30 días)
Shashanka
Shashanka el 13 de Jul. de 2014
Comentada: Roger Stafford el 13 de Jul. de 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 comentario
Azzi Abdelmalek
Azzi Abdelmalek el 13 de Jul. de 2014
It's better to post your code as a text rather than an image

Iniciar sesión para comentar.

Respuestas (2)

Image Analyst
Image Analyst el 13 de Jul. de 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 comentario
Image Analyst
Image Analyst el 13 de Jul. de 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/

Iniciar sesión para comentar.


Roger Stafford
Roger Stafford el 13 de Jul. de 2014
Editada: Roger Stafford el 13 de Jul. de 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 comentario
Roger Stafford
Roger Stafford el 13 de Jul. de 2014
I have corrected the 'while' expression which was in error.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by