3

I'm trying to ouput an array of numbers as a string in MATLAB. I know this is easily done using num2str, but I wanted commas followed by a space to separate the numbers, not tabs. The array elements will at most have resolution to the tenths place, but most of them will be integers. Is there a way to format output so that unnecessary trailing zeros are left off? Here's what I've managed to put together:

data=[2,3,5.5,4];
datastring=num2str(data,'%.1f, ');
datastring=['[',datastring(1:end-1),']']

which gives the output:

[2.0, 3.0, 5.5, 4.0]

rather than:

[2, 3, 5.5, 4]

Any suggestions?

EDIT: I just realized that I can use strrep to fix this by calling

datastring=strrep(datastring,'.0','')

but that seems even more kludgey than what I've been doing.

Doresoom
  • 7,398
  • 14
  • 47
  • 61

2 Answers2

9

Instead of:

datastring=num2str(data,'%.1f, ');

Try:

datastring=num2str(data,'%g, ');

Output:[2, 3, 5.5, 4]

Or:

datastring=sprintf('%g,',data);

Output:[2,3,5.5,4]

Jacob
  • 34,255
  • 14
  • 110
  • 165
3

Another option using MAT2STR:

» datastring = strrep(mat2str(data,2),' ',',')
datastring =
[2,3,5.5,4]

with 2 being the number of digits of precision.

Amro
  • 123,847
  • 25
  • 243
  • 454
  • Note that the number of digits of precision cuts the decimals, too. For example `mat2str(123,2)` returns `1.2e+002`. – JaBe Mar 03 '15 at 16:47