Why does \r (carriage return) also create a new line when printing to the Command Window?

165 views (last 30 days)
There does not seem to be a difference in the use of \n or \r. I would like to see the \r only return a carriage return and not a new line as it does in C.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 3 Mar 2021
Edited: MathWorks Support Team on 3 Mar 2021
This is a problem when using FPRINTF to print to the screen. FPRINTF will work as expected when writing to a file.
In MATLAB 6.1 (R12.1) it is possible to get the effect you are looking for by using '\b' instead of '\r', where '\b' is the escape character for a single character backspace.
You will need to change the code a little to adjust to the '\b'. Following is an illustrative example:
ix = 1;
chars='|/-\';
fprintf(1,'%c', chars(ix)); % new line
while(1)
fprintf(1,'\b%c', chars(ix)); % modified line
ix = mod(ix,4)+1;
pause(0.05);
end
If multiple spaces need to be deleted, you may use the following code fragment:
for ix=1:numspaces
fprintf('\b')
end
  1 Comment
Shlomo Geva
Shlomo Geva on 13 Feb 2021
Edited: Shlomo Geva on 14 Feb 2021
Here is an example of a simple loop progress monitor using \b
% note multiple spaces at the end - that's a scratchpad area
fprintf('Progress: ');
N=23; % number of iterations in the loop
for i=1:N
% backspace 6 positions before printing %5.2f%% (uses 6 positions)
fprintf('\b\b\b\b\b\b%5.2f%%', i / N * 100);
pause(1);
end
fprintf('\nDone\n');

Sign in to comment.

More Answers (1)

Andrew Potvin
Andrew Potvin on 14 Apr 2017
Edited: MathWorks Support Team on 2 Mar 2021
This has been a known problem/bug since at least 1998.
I don't have the latest MATLAB, but it was still a bug in MATLAB 2012a. The \r escape code works as expected in Octave (version 4.2.1, perhaps before).
HTH,
Andy Potvin

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!