Jonathan H
Jonathan H

Reputation: 7943

num2str sets a constant width for integer formatting

I am using num2str to print an array of integers. My problem is that the format %d, (notice no flag or field width) doesn't yield a comma-separated list of values as I would expect.

Instead, it seems that all elements are forced to the same width by introducing spaces. I would like to get rid of these spaces. For example:

>> num2str(randi(10,1,10),'%d,')
7, 8,10,10, 2, 2, 7, 1, 6, 6,

>> num2str(randi(10,1,10),'%d,')
9,5,4,7,8,6,4,2,6,3,

In the first example, you can see that all elements have a width of 2 -- this is the largest width among all elements, but I would prefer the output list to be compact: 7,8,10,10,2,2,7,1,6,6,. In the second example, the largest width is 1, and there are no spaces introduced. I don't understand why Matlab would force all elements to have equal field length.

Upvotes: 1

Views: 1183

Answers (1)

marsei
marsei

Reputation: 7751

num2str computes the max of the vector, and pads with white space numbers that have less digits (type edit num2str in the command window to see the source code).

Try sprintf instead,

sprintf('%d,', randi(1000,1,10))

Upvotes: 2

Related Questions