Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In Matlab I have integer array a=[1 2 3]. I need to convert them into one string, separated by ',':

c = '1,2,3' 

If somehow I can have a string array b=['1' '2' '3'], then I can use

c = strjoin(b, ',')

to achieve the goal.

So my question is: How to convert integer array a=[1 2 3] into a string array b=['1' '2' '3']?

The int2str() is not working. It will give out

'1 2 3'

and it is not a "string array", so the strjoin can not apply to it to achieve '1,2,3'

share|improve this question
 
Thanks for the 3 answers that can get the c = '1,2,3' . But my own answer below is the only one that actually "convert int array into string array" :) –  Ben Lin Jun 5 '13 at 1:40
add comment

4 Answers

up vote 2 down vote accepted

You can simply use sprintf():

a = 1:3;
c = sprintf('%d,',a);
c = c(1:end-1);
share|improve this answer
 
+1 - I did not know this! –  n00dle Jun 4 '13 at 22:53
add comment

There's a function in the file exchange called vec2str that'll do this.

You'll need to set the encloseFlag parameter to 0 to remove the square brackets. Example:

a = [1 2 3];
b = vec2str(a,[],[],0);

Inside b you'll have:

b = 
    '1,2,3'
share|improve this answer
 
sounds good, but not as simple as Oleg's solution, especially when it requires downloading a file :) –  Ben Lin Jun 4 '13 at 23:10
add comment

I found one solution myself:

after getting the string (not array), split it:

b = int2str();   %b='1  2  3'
c = strsplit(b); %c='1' '2' '3'

Then I can get the result c=strjoin(c, ',') as I wanted.

share|improve this answer
add comment

You can use:

c = regexprep(num2str(a), '\s*', ',');
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.