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?
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.
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.
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.
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]
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'
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}]}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With