Need helping finding the source of the forever loop in my code

1 visualizzazione (ultimi 30 giorni)
I'm writing a code that reads an rnx file and sorts the data based off the satellite constellation. My code runs without error but seems to have a forevor loop somewheres bc the code never completes running

Risposta accettata

Image Analyst
Image Analyst il 13 Lug 2020
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?

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by