Newlines and spaces in strings

8 views (last 30 days)
JM
JM on 2 Aug 2011
Hello,
The following code creates a string, disp_string, to be displayed in a GUI text field:
% dist_f is a function that outputs an array of values to be printed
totals = dist_f(t,step);
for i = 1:length(totals),
numstr = sprintf('%.2f', totals(i), '\n');
disp_string = strcat(disp_string, numstr, ' ');
end
disp_string = strcat('Distances: ', disp_string);
% display disp_string on the GUI
set(handles.stats_text,'String',disp_string);
I would like what appears on the GUI to look like, for example,
Distances: 6.60
32.00
10.44
32.00
with the nice newlines after each distance, but instead it displays
Distances:6.6032.0010.4432.00
without any newlines or spaces anywhere. I've got the formatting all wrong, I think. What am I doing wrong / is this the wrong way to do this?
Thanks in advance for help!

Accepted Answer

Jan
Jan on 2 Aug 2011
Append the newline to the format string:
...
numstr = sprintf(' %.2f\n', totals(i));
...
I'm not sure, where you want to have the space.
SPRINTF can handle vectors also, such that you can omit the FOR loop:
totals = dist_f(t,step);
disp_string = ['Distances: ', sprintf(' %.2f\n', totals)];
  1 Comment
JM
JM on 2 Aug 2011
The first suggestion didn't work but the second one does, thanks! I didn't think of using sprintf with an array.
Do you know if it's possible to select and copy the text on a GUI? I can't so I just print the text to the console.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Identification in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!