Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a vector with variable number of elements using sprintf

Tags:

printf

matlab

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?

like image 888
Maddy Avatar asked May 16 '11 23:05

Maddy


People also ask

How do I print the contents of a vector file?

In the for loop, size of vector is calculated for the maximum number of iterations of loop and using at(), the elements are printed. for(int i=0; i < a. size(); i++) std::cout << a.at(i) << ' '; In the main() function, the elements of vector are passed to print them.

What is sprintf ()?

sprintf stands for “String print”. Instead of printing on console, it store output on char buffer which are specified in sprintf.

What does sprintf do in R?

sprintf() function in R Language uses Format provided by the user to return the formatted string with the use of the values in the list.


2 Answers

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
like image 117
gnovice Avatar answered Nov 12 '22 08:11

gnovice


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
like image 36
abcd Avatar answered Nov 12 '22 07:11

abcd