TYL
TYL

Reputation: 1637

Combine a cell array or strings into a single space separated string

How do I combine cells in a cell array to form a one single cell? For e.g.:

a = {'I', 'am', 'a', 'noob', 'in', 'matlab'}

into 1 cell

a = 'I am a noob in matlab'

Upvotes: 1

Views: 2171

Answers (2)

Dan
Dan

Reputation: 45752

NOTE Luis Mendo's answer of strjoin below is clearly better, however I can't delete this while it is the accepted answer.


First you need to add a row of space characters:

a = {'I', 'am', 'a', 'noob', 'in', 'matlab'}
a(2,:) = {' '}

And now you can use the {:} operation to get a comma separated list and the [] operation to concatenate these:

[a{:}]

ans = 

I am a noob in matlab

Note that this works out because Maltab is column-major which is why when you "linearize" a matrix using the : operator, it goes down the columns first before going across the rows.

Also note that this method is slightly flawed in that it adds one extra space character to the end of the result. So you might want to trim it.

Last thing to note is that you asked for the answer to be in one cell but I gave you a char array. If you really want it in a cell, which I'm sure you don't, then do this:

{[a{:}]}

Upvotes: 4

Luis Mendo
Luis Mendo

Reputation: 112689

strjoin does exactly that:

>> a = {'I', 'am', 'a', 'noob', 'in', 'matlab'}
a = 
    'I'    'am'    'a'    'noob'    'in'    'matlab'
>> strjoin(a)
ans =
I am a noob in matlab

Upvotes: 6

Related Questions