How do I overwrite text in the command window?
Mostrar comentarios más antiguos
I am trying to write a counter that uses the format "processing subject ### of 123", where the ### changes in the command window upon every subject change. I know this could be accomplished in a loop with something like
fprintf('processing subject 000 of 123')
for number in 1:123
fprintf('\b\b\b\b\b\b\b\b\b\b%s of 123',subnum(number))
% subnum is a 3-digit number in character form to preserve the 3-digit format declared elsewhere
end
But that is ugly and terribly inefficient. How do I rectify the problem?
Respuesta aceptada
Más respuestas (4)
Eeshan Bhatt
el 25 de Oct. de 2018
Editada: Eeshan Bhatt
el 25 de Oct. de 2018
I know you have an accepted answer, but here's a quick robust code that I use often.
nbytes = fprintf('processing 0 of %d', length(z));
for nz = z
while nbytes > 0
fprintf('\b')
nbytes = nbytes - 1;
end
nbytes = fprintf('processing %d of %d', nz, length(z));
% YOUR PROCESS HERE
%
%
%
end
1 comentario
Ted Shultz
el 19 de Jul. de 2019
Editada: Ted Shultz
el 19 de Jul. de 2019
Eeshan, this is a nice solution! I would propose this small modification so that it runs a little faster, and is a little simpler:
nbytes = fprintf('processing 0 of %d', length(z));
for nz = z
fprintf(repmat('\b',1,nbytes))
nbytes = fprintf('processing %d of %d\n', nz, length(z));
% YOUR PROCESS HERE
%
%
%
end
Fangjun Jiang
el 10 de Jul. de 2017
1 voto
or go fancy, waitbar()
1 comentario
Kyle Poe
el 11 de Jul. de 2017
Boubat Matthieu
el 28 de Jul. de 2020
I packaged the use of fprintf('\b') 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:
prefix = 'processing subject ';
suffix = ' of 123';
progression = UpdatableText(prefix,suffix); % UpdatableText is the actual class
for i = 1:123
progression.print(num2str(i));
end
There are also methods to easily add a percent value and a progress bar.
Cristi Savlovschi
el 15 de Jul. de 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;
Categorías
Más información sobre Environment and Settings en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!