3

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'

1
  • 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" :) Commented Jun 5, 2013 at 1:40

4 Answers 4

4

You can simply use sprintf():

a = 1:3;
c = sprintf('%d,',a);
c = c(1:end-1);
Sign up to request clarification or add additional context in comments.

Comments

2

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'

1 Comment

sounds good, but not as simple as Oleg's solution, especially when it requires downloading a file :)
2

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.

Comments

2

You can use:

c = regexprep(num2str(a), '\s*', ',');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.