How do I show a changing variable value in command window?

I am doing kind of Genetic Algorithm problem. It takes dozens of iterations before coming to a satisfactory solution. I want to show how the number of iteration grows IN ONE ROW in the command window.
I only know how to do it in rows one after another, here's the code:
if %Stopping Criterion%
break;
else
iteration = iteration +1 ;
fprintf('Iteration = %d \n',iteration);
end
As you know , in the command window, this will be:
Iteration = 2
Iteration = 3
Iteration = 4
Iteration = 5
Iteration = 6
Iteration = 7
.
.
.
My concern is, I want to display the result ONLY IN ONE ROW, that is, "Iteration =" does not show again, ONLY the growing value of the iteration changes.
How could I make it?
Thanks in advance:)

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 16 Mär. 2014
Before you start the loop,
fprintf('Iteration =');
In the loop,
fprintf(' %d', iteration);
after the loop:
fprintf('\n');

6 Kommentare

Hi Walter,
I just tried, and it turned out to be this way:
Iteration =2
3
4
5
6
7
.
.
I want the "Iteration =" stays there, only the number changes, as if it blinks.
Anyway, thank you!
I am sorry, I put the
fprintf('\n');
just before the end of loop.
but even if I put it after the loop, the numbers still come one after another, in this way: Iteration =234567891011
This is not what I want..
Did you miss the space before the %d ?
If you want the number to increase "in place" on the line, then,
before the loop
fprintf('iteration = 0000');
in the loop:
fprintf('\b\b\b\b%4d', iteration);
after the complete loop has ended
fprintf('\n');
That works!!
Thank you, Master Walter!
BTW, could you explain how does this work? I've no idea about the 0000 and \b\b\b\b stuff..
The 0000 is not important other than it being 4 characters long so that you get positioned at the right position. Each \b backspaces one position so \b\b\b\b moves to the beginning of those 4 positions. The %4d says to use 4 characters (more if needed) to output the number... leaving you at the same position on the screen as you were after the 0000 . Thus each line after that backs up over the previous number and puts in a new 4 character number.
If your iteration count might exceed 9999 then you would need to increase the number of characters initially printed and you would need to add more \b
Perfect teacher!
Thanks again!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Entering Commands finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 16 Mär. 2014

Kommentiert:

am 16 Mär. 2014

Community Treasure Hunt

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

Start Hunting!

Translated by