Newlines and spaces in strings

5 Ansichten (letzte 30 Tage)
JM
JM am 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!

Akzeptierte Antwort

Jan
Jan am 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 Kommentar
JM
JM am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by