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
?
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.
sprintf stands for “String print”. Instead of printing on console, it store output on char buffer which are specified in sprintf.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With