Home > Back-end >  Concatenate cell array in MATLAB
Concatenate cell array in MATLAB

Time:05-26

In Matlab you can concatenate arrays by saying:

a=[];
a=[a,1];

How do you do something similar with a cell array?

a={};
a={a,'asd'};

The code above keeps on nesting cells within cells. I just want to append elements to the cell array. How do I accomplish this?

CodePudding user response:

If a and b are cell arrays, then you concatenate them in the same way you concatenate other arrays: using []:

>> a={1,'f'}
a =
  1×2 cell array
    {[1]}    {'f'}

>> b={'q',5}
b =
  1×2 cell array
    {'q'}    {[5]}

>> [a,b]
ans =
  1×4 cell array
    {[1]}    {'f'}    {'q'}    {[5]}

You can also use the functional form, cat, in which you can select along which dimension you want to concatenate:

>> cat(3,a,b)
  1×2×2 cell array
ans(:,:,1) = 
    {[1]}    {'f'}

ans(:,:,2) = 
    {'q'}    {[5]}

To append a single element, you can do a=[a,{1}], but this is not efficient (see this Q&A). Instead, do a{end 1}=1 or a(end 1)={1}.


Remember that a cell array is just an array, like any other. You use the same tools to manipulate them, including indexing, which you do with (). The () indexing returns the same type of array as the one you index into, so it returns a cell array, even if you index just a single element. Just about every value in MATLAB is an array, including 6, which is a 1x1 double array.

The {} syntax is used to create a cell array, and to extract its content: a{1} is not a cell array, it extracts the contents of the first element of the array.

{5, 8, 3} is the same as [{5}, {8}, {3}]. 5 is a double array, {5} is a cell array containing a double array.

a{5} = 0 is the same as a(5) = {0}.

  • Related