views:

350

answers:

2

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.

+3  A: 

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
+2  A: 

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