MATLAB: Need helping finding the source of the forever loop in the code

failsafeforever loopinfinite loop

Question Complete

Best Answer

Usually when there is an infinite loop it's with a while loop that never met the condition to exit, and (importantly!) didn't have a failsafe. Your while loops do not have a failsafe to prevent an infinite loop, as all while loops should have. Let's say that you know the while loop should iterate about 1000 times, and that if it goes over 50,000, something's definitely wrong. So you must have a loop counter and a check that the loop counter does not exceed your max iteration count. Modify your loops to add a failsafe like this:
maxIterations = 50000; % Some big number that you know should never be reached.
loopCounter = 1;
while someCondition && loopCounter <= maxIterations
fprintf('Starting iteration #%d.\n', loopCounter);
% Some code to generate a new value for someCondition.
% Increment the loop counter:
loopCounter = loopCounter + 1;
end
if loopCounter >= maxIterations
warningMessage = sprintf('Loop terminated early after %d iterations', loopCounter - 1);
uiwait(warndlg(warningMessage));
end
Now, after you've made those modifications, what do you see? It should kick out after it hits the max iteration number. Does it? Why? You should check the condition for when the two loops you have should exit. Are they ever met?