问题
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.
回答1:
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]
回答2:
Another option using MAT2STR:
» datastring = strrep(mat2str(data,2),' ',',')
datastring =
[2,3,5.5,4]
with 2
being the number of digits of precision.
来源:https://stackoverflow.com/questions/3057618/how-to-format-output-using-matlabs-num2str