MATLAB: How to have the loop counters with nested loops to display on one line in the Command Window without carriage return

commandcounterfprintflineMATLABsamewindow

I have the following nested loops, where I am calling some function and doing some processing inside the nested loop.
I want to be able to see which iteration of the nested loops I am currently at. I do not want each iteration to be printed to a new line in the Command Window.
for i = 1:10
for j = 1:10
formatSpec = '%d %d\n';
fprintf(formatSpec, i,j);
% do some work
end
end

Best Answer

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.
It works by keeping track of the length of the printed string in "FPRINTF_LENGTH", and using the backspace escape command in a for loop that runs for "FPRINTF_LENGTH" number of iterations.
FPRINTF_LENGTH=0;
for i = 1:10
for j = 1:10
for k=1:FPRINTF_LENGTH
fprintf('\b'); % backspacing previous counter value
end
formatSpec = '%d %d';
FPRINTF_LENGTH = fprintf(formatSpec, i,j);
pause(.05) % to have sufficient time to render each iteration on the screen.
end
end