Next: , Previous: Data Structures, Up: Data Containers


6.2 Cell Arrays

It can be both necessary and convenient to store several variables of different size or type in one variable. A cell array is a container class able to do just that. In general cell arrays work just like N-dimensional arrays, with the exception of the use of `{' and `}' as allocation and indexing operators.

As an example, the following code creates a cell array containing a string and a 2-by-2 random matrix

     c = {"a string", rand(2, 2)};

And a cell array can be indexed with the { and } operators, so the variable created in the previous example can be indexed like this

     c{1}
          => ans = a string

As with numerical arrays several elements of a cell array can be extracted by indexing with a vector of indexes

     c{1:2}
          => ans =
     
               (,
                 [1] = a string
                 [2] =
     
                    0.593993   0.627732
                    0.377037   0.033643
     
               ,)

The indexing operators can also be used to insert or overwrite elements of a cell array. The following code inserts the scalar 3 on the third place of the previously created cell array

     c{3} = 3
          => c =
     
              {
                [1,1] = a string
                [1,2] =
     
                   0.593993   0.627732
                   0.377037   0.033643
     
                [1,3] =  3
              }

In general nested cell arrays are displayed hierarchically as above. In some circumstances it makes sense to reference them by their index, and this can be performed by the celldisp function.

— Function File: celldisp (c, name)

Recursively display the contents of a cell array. By default the values are displayed with the name of the variable c. However, this name can be replaced with the variable name.

     
     
See also: disp.