Print a vector with variable number of elements using sprintf

The simplest answer is to note that SPRINTF will automatically cycle through all the elements of a vector you give it, so you only have to use one %d, but follow it or lead it with a space. Then you can remove extra white space on the ends using the function STRTRIM. For example:

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

ans =

123 456 789

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

Tags:

Printf

Matlab