Print vector with variable number of elements using sprintf

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

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

How can I do this without typing so many %d in the number of elements in item ?

+8
printf matlab
source share
2 answers

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

 >> item = [123 456 789]; >> strtrim(sprintf('%d ',item)) ans = 123 456 789 
+19
source share

I believe num2str is what you are looking for.

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

Since you also tagged it with sprintf , a solution is used here 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 
+4
source share

All Articles