Is it possible to rewrite/update a printed line?
Ältere Kommentare anzeigen
I want to simulate a progress bar during the run, so 1% has to be updated to 2% for example
2 Kommentare
per isakson
am 13 Dez. 2017
Bearbeitet: per isakson
am 19 Dez. 2017
Mr M.
am 18 Dez. 2017
Akzeptierte Antwort
Weitere Antworten (3)
Valerio Pampanoni
am 25 Jan. 2019
Bearbeitet: Valerio Pampanoni
am 25 Jan. 2019
I know it is a little late, but I asked myself the same question while editing a very large code and I found my own solution which involves using the fprintf function and the backspace character '\b'. I tried to use the waitbar function, but it slows down the code so much it is not viable at all.
imax = 100;
prog = 0;
fprintf(1,'Computation Progress: %3d%%\n',prog);
for k = 1:1:imax
prog = ( 100*(k/imax) );
fprintf(1,'\b\b\b\b%3.0f%%',prog); pause(0.1); % Deleting 4 characters (The three digits and the % symbol)
end
fprintf('\n'); % To go to a new line after reaching 100% progress
Note how I need to use 4 backspace characters to delete the previous progress and two percent characters to write the percent symbol at the end of the line. But the most important part is the fact that you must use the handle on the fprintf function to update the previous statement.
Works on Matlab 2018b Update 2.
Edit: rather than using the floor function, I simply display the first three digits of the floating point number 'prog', saving a little computation time.
2 Kommentare
Dominik Braun
am 5 Feb. 2021
Thanks, that was very helpful
NV
am 13 Feb. 2025
very nice, thanks!
Boubat Matthieu
am 28 Jul. 2020
I packaged the use of fprintf('\b'), which delete the last character in the command window, into a class hoping that it will ease the way to rewrite/update text in the command window. If you want to give it a try it's available here.
It goes like this:
progression = UpdatableText; % UpdatableText is the actual class
for i = 1:100
progression.print(sprintf('step %d/100',i));
end
There are also methods to easily add a percent value and a progress bar.
Cristi Savlovschi
am 15 Jul. 2021
Bearbeitet: Cristi Savlovschi
am 15 Jul. 2021
function dispProgressMsg(msg)
ASCII_BKSP_CHAR = 8;
persistent prevMsgLen;
if isempty(prevMsgLen)
prevMsgLen = 0;
end
disp([ char(repmat(ASCII_BKSP_CHAR,1,prevMsgLen)) msg]);
prevMsgLen = numel(msg)+1;
Kategorien
Mehr zu App Building finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!