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

250 views (last 30 days)
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 Comments
Wing Lin
Wing Lin on 7 Oct 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 on 7 Oct 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).

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 21 Feb 2013
Edited: Image Analyst on 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 Comments
Walter Roberson
Walter Roberson on 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);

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!