recipes : programming : Concatenating cell arrays


How do I concatenate two cell arrays?


Simply use the concatenation operator [ ].


ans = 

    'one'    'two'    'three'    'four'

This one can be confusing when you're starting out with MATLAB. You have to remember that square brackets are a concatenation operator. So just like the * is an operator used to multiply one number by another, [ ] is used to concatenate things. You literally can read square brackets as meaning "turn the stuff inside these brackets into a single array." Of course it must be possible for what's inside the square brackets to be turned into an array:

%We can make A and B into a 2-D matrix because they each have the same number of columns.
>> A=[1,3,6];
>> B=[10,30,60];
>> C=[A;B]

C =

     1     3     6
    10    30    60

%This fails because the lengths of A and B differ.
>> A=[1,3,6,12,24];
>> B=[10,30,60];
>> C=[A;B]
Error using vertcat
CAT arguments dimensions are not consistent.

Remember not to confuse [ ] with ( ), which is used for grouping commands. e.g. 3*2^2 is 12 but (3*2)^2 is 36.