Ben Lin
Ben Lin

Reputation: 835

Matlab: convert int array into string array?

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'

Upvotes: 3

Views: 3616

Answers (4)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

You can use:

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

Upvotes: 2

Ben Lin
Ben Lin

Reputation: 835

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.

Upvotes: 2

Oleg
Oleg

Reputation: 10676

You can simply use sprintf():

a = 1:3;
c = sprintf('%d,',a);
c = c(1:end-1);

Upvotes: 4

n00dle
n00dle

Reputation: 6043

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'

Upvotes: 2

Related Questions