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.

2 Answers 2

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]

Sign up to request clarification or add additional context in comments.

Comments

4

Another option using MAT2STR:

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

with 2 being the number of digits of precision.

1 Comment

Note that the number of digits of precision cuts the decimals, too. For example mat2str(123,2) returns 1.2e+002.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.