How to format output using MATLAB's num2str
Posted
by Doresoom
on Stack Overflow
See other posts from Stack Overflow
or by Doresoom
Published on 2010-06-16T22:26:57Z
Indexed on
2010/06/16
22:52 UTC
Read the original article
Hit count: 341
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.
© Stack Overflow or respective owner