Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontally concatenate cell array of strings

Tags:

matlab

I wish to horizontally concatenate lines of a cell array of strings as shown below.

start = {'hello','world','test';'join','me','please'}

finish = {'helloworldtest';'joinmeplease'}

Are there any built-in functions that accomplish the above transformation?

like image 374
Chris R Avatar asked Feb 01 '11 22:02

Chris R


People also ask

How do you concatenate strings in an array?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

How do I concatenate horizontally in Matlab?

C = horzcat( A , B ) concatenates B horizontally to the end of A when A and B have compatible sizes (the lengths of the dimensions match except in the second dimension). C = horzcat( A1,A2,…,An ) concatenates A1 , A2 , … , An horizontally.

Which of the following can be used for horizontal concatenation of given strings A and B?

You can use the square bracket operator [] to concatenate or append arrays. For example, [A,B] and [A B] concatenates arrays A and B horizontally, and [A; B] concatenates them vertically.

What is concatenation in Matlab?

You can also use square brackets to append existing matrices. This way of creating a matrix is called concatenation. For example, concatenate two row vectors to make an even longer row vector. A = ones(1,4); B = zeros(1,4); C = [A B]


2 Answers

There is an easy non-loop way you can do this using the functions NUM2CELL and STRCAT:

>> finish = num2cell(start,1);
>> finish = strcat(finish{:})

finish = 

    'helloworldtest'
    'joinmeplease'
like image 106
gnovice Avatar answered Oct 19 '22 00:10

gnovice


A simple way is too loop over the rows

nRows = size(start,1);
finish = cell(nRows,1);

for r = 1:nRows
    finish{r} = [start{r,:}];
end

EDIT

A more involved and slightly harder to read solution that does the same (the general solution is left as an exercise for the reader)

finish = accumarray([1 1 1 2 2 2]',[ 1 3 5 2 4 6]',[],@(x){[start{x}]})

like image 45
Jonas Avatar answered Oct 18 '22 23:10

Jonas