1

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?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
berala
  • 55
  • 5

1 Answers1

5

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}.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • Nice answer. Nitpick: I believe it is "Every _variable_ is an array". Functions, methods, etc. are not. – Stewie Griffin May 25 '22 at 10:11
  • @StewieGriffin Thanks for pointing that out. I guess it's a bit more nuanced than I made it out to be. A function handle also is not an array, so not even all variables are arrays. I guess I shouldn't generalize... :) – Cris Luengo May 25 '22 at 11:41
  • 1
    @Sardar just pointed out that, yes, a function handle is technically also an array. It's just that you can't put more than one handle in the array. So a function handle is array limited to 1x1. – Cris Luengo May 25 '22 at 20:02