How to display the number of iterations a while loop does?

41 Ansichten (letzte 30 Tage)
Katherine
Katherine am 21 Feb. 2013
Kommentiert: Walter Roberson am 1 Jan. 2021
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 Kommentare
Wing Lin
Wing Lin am 7 Okt. 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
Image Analyst am 7 Okt. 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).

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Image Analyst
Image Analyst am 21 Feb. 2013
Bearbeitet: Image Analyst am 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 Kommentare
Niklas Kurz
Niklas Kurz am 1 Jan. 2021
How to display just the total count-number?
Walter Roberson
Walter Roberson am 1 Jan. 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);

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by