How to display the number of iterations a while loop does?
41 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I'm trying to display the number of iterations a while loop goes through but I can't seem to figure it out. here's my code so far:
P = 250000;
A = 25000;
I = 4.5/100;
while P > A;
P = P*(1+I)-A;
P = P + 1;
end
I'm getting the correct amount of iterations but its outputting it as the 14 actual values rather than "14"
thanks
2 Commenti
Wing Lin
il 7 Ott 2017
You can create a separate variable to store the number of iterations that your loop has run. For example,
count = 0; % kind of important to start at 0 for an accurate count
loopStart = 1; % arbitrary
loopEnd = 10; % arbitrary
while loopStart < loopEnd
count = count + 1; % this increments by 1 each time the loop executes
loopStart = loopStart + 5; % 5 is just some arbitrary constant that I chose to increment by
end
count % this should display 2 for this specific example
Image Analyst
il 7 Ott 2017
Since this is your answer, Wing, you should put it down in the Answers section, so you can get credit for it, rather than as a comment up here (which is usually just used to ask the poster for clarification of the question).
Risposte (1)
Image Analyst
il 21 Feb 2013
Modificato: Image Analyst
il 13 Apr 2019
Try adding a loop counter:
P = 250000;
A = 25000;
I = 4.5/100;
counter = 1;
while P > A
P = P*(1+I)-A;
P = P + 1;
fprintf('Just finished iteration #%d\n', counter);
counter = counter + 1;
end
4 Commenti
Walter Roberson
il 1 Gen 2021
P = 250000;
A = 25000;
I = 4.5/100;
counter = 1;
while P > A && counter < 10
P = P*(1+I)-A;
P = P + 1;
counter = counter + 1;
end
fprintf('finished %d iterations\n', counter);
Vedere anche
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!