How can I have my loop counter display on one line instead of printing carriage returns in MATLAB 7.8 (R2009a)?
41 views (last 30 days)
Show older comments
MathWorks Support Team
on 16 Jun 2010
Edited: MathWorks Support Team
on 19 Apr 2023
I print a counter in my loop in the MATLAB command window to keep track of its progress while running. If I use the following code:
for i=1:10
i
end
there are several carriage returns in the command window in addition to the counter number. I would like to have the counter numbers displayed on one line.
Accepted Answer
MathWorks Support Team
on 18 Apr 2023
Edited: MathWorks Support Team
on 19 Apr 2023
In MATLAB 7.8 (R2009a) loop counter values can be displayed in the command window without carriage returns by using the FPRINTF command.
The following code displays counter values with a space between each successive value instead of a carriage return.
for i=1:10
fprintf('%d ', i);
end
The following modified version of the code above uses the backspace escape command '\b' to delete the previous counter value. This increments the counter in place rather than in a line of increasing length.
fprintf('\nCounter: ')
for i=1:100
if i>1
for j=0:log10(i-1)
fprintf('\b'); % delete previous counter display
end
end
fprintf('%d', i);
pause(.05); % allows time for display to update
end
fprintf('\n')
An implementation of a redefinition of FPRINTF for carriage return without linefeed has been published on the following MATLAB Central file:
Note that MathWorks does not guarantee or warrant the use or content of these submissions. Any questions, issues, or complaints should be directed to the contributing author.
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!