recipes : Text Processing : Overwriting text output at the command line


You want to display the status of your program to the command line but don't to bring up a new line each time you post an update.


The trick is to use the back-space character, "\b" and the fprintf command. You can use fprintf rather like disp, but it gives you more control as it doesn't add a new-line (\n) by default and provides the formatting options also present in sprintf. Here's a quick example of fprintf:

fprintf('Processing data')	
for ii=1:10

You will want to run that example from an .m file rather than typing it into the command line because otherwise the effect of the last line is lost. You will see a line of 10 dots appear over a period of 5 seconds. Then on a new line the word "Done!" will appear. This can make a nice alternative to a waitbar, because it doesn't bring up a new window and uses up fewer resources. Now let's modify this example using the backspace character to make a nicer wait-bar alternative. This must be run from within an m file. (text_wait.m)

fprintf(['|',repmat('-',1,reps),'|']) %make the "background"
fprintf(repmat('\b',1,reps+1)) %send the cursor back to the start

for ii=1:reps


This function creates a "background" resembling this: |----------|, and gradually fills it with * symbols: |****------|


You can use the back-space character to make a generic function that allows you overwrite any text on the command line. To try it out, download chalk.m and demo_chalk.m. Put them both in your path and run demo_chalk.