Displaying information from MATLAB without a line

2020-06-08 23:30发布

问题:

Is there any way to output/display information from a MATLAB program without an ending line feed?

My MATLAB program outputs a number a bit now and then. Between outputting the number the program does a lot of other stuff. This is a construct mainly to indicate some kind of progress and it would be nice not to have a line feed each time, just to make it more readable for the user. This is approximately what I'm looking for:

Current random seed:
4 7 1 1 

The next output from the program would be on the same row if it is still doing the same thing as before.

I've read the doc on disp, sprintf, and format but haven't found what I'm looking for. This doesn't mean it isn't there. ;)

回答1:

The fprintf function does not add a line feed unless you explicitly tell it to. Omit the fid argument to have it print to the Command Window.

fprintf('Doing stuff... ');
for i = 1:5
    fprintf('%d ', i);
    % do some work on that pass...
end
fprintf(' done.\n'); % That \n explicitly adds the linefeed

Using sprintf won't quite work: it creates a string without a line feed, but then if you use disp() or omit the semicolon, disp's own display logic will add a line feed.