11

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?

3 Answers 3

22

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'
Sign up to request clarification or add additional context in comments.

Comments

1

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}]})

3 Comments

Thanks, it works, I spent the last 20 minutes trying to do it with vectorization - I can't remember the last time I actually have used a loop in Matlab :)
@Chris R: As you can see, there is a non-loop solution using accumarray, though you might not want to use that. Anyway, if the loop doesn't make too many function calls, it is usually reasonably fast in newer versions of Matlab.
@ChrisR: if you dont like the for-loop, you can write in one line as: finish = arrayfun(@(i)[start{i,:}], 1:size(start,1), 'UniformOutput',false)';
-1

I think you want is that these two are concatenated as a single cell array. Try using this code, works for me.

'x = [{start}, {finish}];'

2 Comments

the example variable finish was intended to be the output (the end result). It is not supposed to be part of the inputs.
Simple replace 'X' by 'finish'

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.