How to format output using MATLAB num2str

I am trying to output an array of numbers as a string in MATLAB. I know this is easy to do using num2str, but I need commas and then a space to separate the numbers, not the tabs. The elements of the array in most cases will have permission to tenth place, but most of them will be integers. Is there a way to format the output so that extra trailing zeros are stopped? Here is what I managed to collect:

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

which gives the result:

[2.0, 3.0, 5.5, 4.0]

but not:

[2, 3, 5.5, 4]

Any suggestions?

EDIT: I just realized what I can use strrepto fix this by calling

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

but it seems even more meaningful than what I did.

+3
2

:

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

:

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

: [2, 3, 5.5, 4]

:

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

: [2,3,5.5,4]

+9

, MAT2STR:

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

2 .

+3

Source: https://habr.com/ru/post/1750391/


All Articles