Next: , Up: Cell Arrays   [Contents][Index]


6.3.1 Basic Usage of Cell Arrays

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

To access the elements of a cell array, it can be indexed with the { and } operators. Thus, 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 = a string
     ⇒ ans =

               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
         }

Details on indexing cell arrays are explained in Indexing Cell Arrays.

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

celldisp (c)
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. For example:

c = {1, 2, {31, 32}};
celldisp (c, "b")
   ⇒
      b{1} =
       1
      b{2} =
       2
      b{3}{1} =
       31
      b{3}{2} =
       32

See also: disp.

To test if an object is a cell array, use the iscell function. For example:

iscell (c)
     ⇒ ans = 1

iscell (3)
     ⇒ ans = 0

iscell (x)

Return true if x is a cell array object.

See also: ismatrix, isstruct, iscellstr, isa.


Next: , Up: Cell Arrays   [Contents][Index]