MATLAB: List of lists while loop
arrayhomeworklist of listsMATLABwhile
Related Solutions
Try this:
again = true; % Flag for iterating the outer while loop again.
loopCounter1 = 1; % Count iterations to prevent infinite loop. This is a "fail safe".
loopCounter2 = 1; % Count iterations to prevent infinite loop. This is a "fail safe".maxIterations = 9999; % Whatever is the most you ever expect.
while condition1 && again && loopCounter1 < maxIterations while condition2 && loopCounter2 < maxIterations if condition3 % statements
% increment counter
break; % Breaks out of inner while loop only, loop #2.
else % Here i want to break out without return to any while
again = false; % Make sure outer while loop does not iterate again.
break; end % Increment counter
loopCounter2 = loopCounter2 + 1; end % Increment counter loopCounter1 = loopCounter1 + 1;end
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;endif 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?
Best Answer