Alex Rivera | Logout

Print a vector with variable number of elements using sprintf

Asked 2011-05-16T23:58:36.043
10

In the following code, I can print all the elements in the vector item separated by a space as

item = [123 456 789];
sprintf('%d %d %d', item)

ans =

123 456 789

How do I go about doing this without having to enter as many %d as the number of elements in item?

Edit
Report

1 Answer

6

I believe num2str is what you're looking for.

item=[123 456 789]; 
num2str(item)

ans =

123  456  789

Since you also tagged it sprintf, here's a solution that uses it.

item=[123 456 789]; 
str='%d ';
nItem=numel(item);
strAll=repmat(str,1,nItem);

sprintf(strAll(1:end-1),item)

ans =

123 456 789
answered 2011-05-17T00:04:41.707

Your Answer