Cell Arrays

Overview

A cell array provides a storage mechanism for dissimilar kinds of data. You can store arrays of different types and/or sizes within the cells of a cell array. For example, you can store a 1-by-50 char array, a 7-by-13 double array, and a 1-by-1 uint32 in cells of the same cell array.

This illustration shows a cell array A that contains arrays of unsigned integers in A{1,1}, strings in A{1,2}, complex numbers in A{1,3}, floating-point numbers in A{2,1}, signed integers in A{2,2}, and another cell array in A{2,3}.

To access data in a cell array, you use the same type of matrix indexing as with other MATLAB® matrices and arrays. However, with cell array indexing, you use curly braces, {}, instead of square brackets or parentheses around the array indices. For example, A{2,3} accesses the cell in row 2 and column 3 of cell array A.

Cell Array Operators

This table shows the operators used in constructing, concatenating, and indexing into the cells of a cell array.

OperationSyntaxDescription
Constructing C = {A B D E}Builds a cell array C that can contain data of unlike types in A, B, D, and E
Concatenating C3 = {C1 C2}Concatenates cell arrays C1 and C2 into a 2–element cell array C3 such that C3{1} = C1 and C3{2} = C2
C3 = [C1 C2]Concatenates the contents of cell arrays C1 and C2
Indexing X = C(s)Returns the cells of array C that are specified by subscripts s
X = C{s}Returns the contents of the cells of C that are specified by subscripts s
X = C{s}(t)
References one or more elements of an array that resides within a cell. Subscript s selects the cell, and subscript t selects the array element(s).

Creating a Cell Array

Creating cell arrays in MATLAB is similar to creating arrays of other MATLAB classes like double, character, etc. The main difference is that, when constructing a cell array, you enclose the array contents or indices with curly braces { } instead of square brackets [ ]. The curly braces are cell array constructors, just as square brackets are numeric array constructors. Use commas or spaces to separate elements and semicolons to terminate each row.

For example, to create a 2-by-2 cell array A, type

A = {[1 4 3; 0 5 8; 7 2 9], 'Anne Smith'; 3+7i, -pi:pi/4:pi};

This results in the array shown below:

For more information on cell arrays, refer to these topics:

Creating Cell Arrays Using Multiple Assignment Statements

You also can create a cell array one cell at a time. MATLAB expands the size of the cell array with each assignment statement:

A(1,1) = {[1 4 3; 0 5 8; 7 2 9]};
A(1,2) = {'Anne Smith'};
A(2,1) = {3+7i};
A(2,2) = {-pi:pi/4:pi};

If you assign data to a cell that is outside the dimensions of the current array, MATLAB automatically expands the array to include the subscripts you specify. It fills any intervening cells with empty matrices. For example, the assignment below turns the 2-by-2 cell array A into a 3-by-3 cell array.

A(3,3) = {5};

3–by-3 Cell Array

Alternative Assignment Syntax.   When assigning values to a cell array, either of the syntaxes shown below is valid. You can use the braces on the right side of the equation, enclosing the value being assigned as shown here:

A(1,1) = {[1 4 3; 0 5 8; 7 2 9]};
A(1,2) = {'Anne Smith'};

Or use them on the left side, enclosing the array subscripts:

A{1,1} = [1 4 3; 0 5 8; 7 2 9];
A{1,2} = 'Anne Smith';

Building Cell Arrays with Concatenation

There are two ways that you can construct a new cell array from existing cell arrays:

Here is an example. First, create three 3-row cell arrays of different widths.

C1 = {'Jan' 'Feb';  '10' '17';  uint16(2004) uint16(2001)};	
C2 = {'Mar' 'Apr' 'May';  '31' '2' '10';  ...
      uint16(2006) uint16(2005) uint16(1994)};
C3 = {'Jun';  '23';  uint16(2002)};

This creates arrays C1, C2, and C3:

      C1                     C2                  C3
'Jan'   'Feb'       'Mar'   'Apr'   'May'       'Jun'
'10'    '17'        '31'    '2'     '10'        '23'
[2004]  [2001]      [2006]  [2005]  [1994]      [2002]

Use the curly brace operator to concatenate entire cell arrays, thus building a 1-by-3 cell array from the three initial arrays. Each cell of this new array holds its own cell array:

C4 = {C1 C2 C3}
C4 = 
    {3x2 cell}    {3x3 cell}    {3x1 cell}

Now use the square bracket operator on the same combination of cell arrays. This time MATLAB concatenates the contents of the cells together and produces a 3-by-6 cell array:

C5 = [C1 C2 C3]
C5 = 
    'Jan'     'Feb'     'Mar'     'Apr'     'May'     'Jun' 
    '10'      '17'      '31'      '2'       '10'      '23'  
    [2004]    [2001]    [2006]    [2005]    [1994]    [2002]

Preallocating Cell Arrays with the cell Function

The cell function enables you to preallocate memory for cell arrays of a specific size. For example, this statement creates a 20-by-30 cell array where each cell of the resulting cell array contains an empty array:

B = cell(20, 30);

Use assignment statements to fill the cells of B.

It is more efficient to preallocate a cell array of a required size using the cell function and then assign data into it, than to grow a cell array as you go along using individual data assignments. The cell function, therefore, offers the most memory-efficient way of preallocating a cell array.

Memory Requirements for Cell Arrays

You do not necessarily need a contiguous block of memory to store a cell array. The memory for each cell needs to be contiguous, but not the entire array of cells.

Referencing Cells of a Cell Array

Because a cell array can contain different types of data stored in various array sizes, cell array indexing is a little more complex than indexing into a numeric or character array.

This section covers the following topics on constructing a cell array:

The examples in this section illustrate how to access the different components of a cell array. All of the examples use the following six-cell array which consists of different classes.

First, build the individual components of the example array:

rand('state', 0);    numArray = rand(3,5)*20;
chArray = ['Ann Lane'; 'John Doe'; 'Al Smith'];
cellArray = {1 4 3 9; 0 5 8 2; 7 2 9 2; 3 3 1 4};
logArray = numArray > 10;

stArray(1).name = chArray(1,:);
stArray(2).name = chArray(2,:);
stArray(1).billing = 28.50;
stArray(2).billing = 139.72;
stArray(1).test = numArray(1,:);
stArray(2).test = numArray(2,:);

and then construct the cell array from these components using the { } operator:

A = {numArray, pi, stArray; chArray, cellArray, logArray};

To see what size and type of array occupies each cell in A, type the variable name alone:

A
A = 
    [3x5 double]    [  3.1416]    [1x2 struct ]
    [3x8 char  ]    {4x4 cell}    [3x5 logical]

Manipulating Cells and the Contents of Cells

When working with cell arrays, you have a choice of selecting entire cells of an array to work with, or the contents of those cells. The first method is called cell indexing; the second is content indexing:

Displaying Parts of the Cell Array.   Using the example cell array A, you can display information on the first row of cells using cell indexing. (The MATLAB colon operator functions the same when used with cell arrays as it does with numeric arrays):

A(1,:)
ans = 
    [3x5 double]    [3.1416]    [1x2 struct]

To display the contents of these cells, use content indexing:

A{1,:}
ans =
   19.0026    9.7196    9.1294    8.8941   18.4363
    4.6228   17.8260    0.3701   12.3086   14.7641
   12.1369   15.2419   16.4281   15.8387    3.5253
ans =
    3.1416
ans = 
1x2 struct array with fields:
    name
    billing
    test

In assignments, you can use content indexing to access only a single cell, not a subset of cells. For example, the statements A{1,:} = value and B = A{1,:} are both invalid. However, you can use a subset of cells any place you would normally use a comma-separated list of variables (for example, as function inputs or when building an array). See Replacing Lists of Variables with Cell Arrays for details.

Assigning Cells.   For cell indexing, assign the double array cell to X:

X = A(1,1)
X = 
    [3x5 double]

X is a 1-by-1 cell array:

whos X
  Name      Size                    Bytes  Class

  X         1x1                       180  cell

For content indexing, assign the contents of the first cell of row 1 to Y:

Y = A{1,1}
Y =
   19.0026    9.7196    9.1294    8.8941   18.4363
    4.6228   17.8260    0.3701   12.3086   14.7641
   12.1369   15.2419   16.4281   15.8387    3.5253

Y is a 3-by-5 double array

whos Y
  Name      Size                    Bytes  Class

  Y         3x5                       120  double

Assigning Multiple Cells.   Assigning multiple cells with cell indexing is similar to assigning a single cell. MATLAB creates a new cell array, each cell of which contains a cell array.

Create a 1-by-2 array with cells from A(1,2) and A(1,3):

X = A(1,2:3)
X = 
    [3.1416]    [1x2 struct]

whos X
  Name      Size                    Bytes  Class

  X         1x2                       808  cell

But assigning the contents of multiple cells returns a comma-separated list. In this case, you need one output variable on the left side of the assignment statement for each cell on the right side:

[Y1 Y2] = A{1,2:3}
Y1 =
    3.1416
Y2 = 
1x2 struct array with fields:
    name
    billing
    test

Working With Arrays Within Cells

Append the parentheses operator to the cell designator A{1,1} to select specific elements of a cell. This example displays specific row and columns of the numeric array stored in cell {1,1} of A:

A{1,1}(2,3:end)
ans =
    0.3701   12.3086   14.7641

Working With Structures Within Cells

Use a combination of indexing operators to access the components of a structure array that resides in a cell of a cell array. The syntax for indexing into field F of a structure array that resides in a cell of array C is

X = C{CellArrayIndex}(StructArrayIndex).F(FieldArrayIndex);

For example, row 1, column 3 of cell array A contains a structure array. Use A{1,3} to select this cell, and .name to display the field name for all elements of the structure array:

A{1,3}.name
ans =
    Ann Lane
ans =
    John Doe

To display all fields of a particular element of the structure array, type

A{1,3}(2)
ans = 
       name: 'John Doe'
    billing: 139.7200
       test: [4.6228 17.8260 0.3701 12.3086 14.7641]

The test field of this structure array contains a 1-by-5 numeric array. Access the odd numbered elements of this field in the second element of the structure array:

A{1,3}(2).test(1:2:end)
ans =
    4.6228    0.3701   14.7641

Working With Cell Arrays Within Cells

The syntax for indexing into a cell array that resides in a cell of array C using content indexing is shown below. To use cell indexing on the inner cell array, replace the curly brace operator enclosing the InnerCellArrayIndes with parentheses.

The syntax for content indexing is

X = C{OuterCellArrayIndex}{InnerCellArrayIndex}

In the example cell array created at the start of this section, A{2,2} is a cell array that resides in a cell of the outer array A. To get the third row of the inner cell array, type

A{2,2}{3,:}
ans =
     7
ans =
     2
ans =
     9
ans =
     2

Note that MATLAB returns a comma-separated list. To have MATLAB return the list of elements as a vector instead, surround the previous expression with square brackets:

[A{2,2}{3,:}]
ans =
     7     2     9     2

Plotting the Cell Array

For a high-level graphical display of cell architecture, use the cellplot function. Consider a 2-by-2 cell array containing two text strings, a matrix, and a vector:

c{1,1} = '2-by-2';
c{1,2} = 'eigenvalues of eye(2)';
c{2,1} = eye(2);
c{2,2} = eig(eye(2));

The command cellplot(c) produces this figure:

Deleting Cells

You can delete an entire dimension of cells using a single statement. Like standard array deletion, use vector subscripting when deleting a row or column of cells and assign the empty matrix to the dimension:

A(cell_subscripts) = []

When deleting cells, curly braces do not appear in the assignment statement at all.

Reshaping Cell Arrays

Like other arrays, you can reshape cell arrays using the reshape function. The number of cells must remain the same after reshaping; you cannot use reshape to add or remove cells:

A = cell(3, 4);

size(A)
ans =
    3     4

B = reshape(A, 6, 2);

size(B)
ans =
    6     2

Replacing Lists of Variables with Cell Arrays

Cell arrays can replace comma-separated lists of MATLAB variables in

If you use the colon to index multiple cells in conjunction with the curly brace notation, MATLAB treats the contents of each cell as a separate variable. For example, assume you have a cell array T where each cell contains a separate vector. The expression T{1:5} is equivalent to a comma-separated list of the vectors in the first five cells of T.

Consider the cell array C:

C(1) = {[1 2 3]};
C(2) = {[1 0 1]};
C(3) = {1:10};
C(4) = {[9 8 7]};
C(5) = {3};

To convolve the vectors in C(1) and C(2) using conv,

d = conv(C{1:2})
d =
     1     2     4     2     3

Display vectors two, three, and four with

C{2:4}
ans = 
    1   0   1

ans = 
    1   2   3   4   5   6   7   8   9   10

ans = 
    9   8   7

Similarly, you can create a new numeric array using the statement

B = [C{1}; C{2}; C{4}]
B =
    1   2   3
    1   0   1
    9   8   7

You can also use content indexing on the left side of an assignment to create a new cell array where each cell represents a separate output argument:

[D{1:2}] = eig(B)
D = 
    [3x3 double]    [3x3 double]

You can display the actual eigenvectors and eigenvalues using D{1} and D{2}.

Applying Functions and Operators

Use indexing to apply functions and operators to the contents of cells. For example, use content indexing to call a function with the contents of a single cell as an argument:

A{1,1} = [1 2; 3 4];
A{1,2} = randn(3, 3);
A{1,3} = 1:5;

B = sum(A{1,1})
B =
     4     6

To apply a function to several cells of an unnested cell array, use a loop:

for k = 1:length(A)
    M{k} = sum(A{1,k});
end

Organizing Data in Cell Arrays

Cell arrays are useful for organizing data that consists of different sizes or kinds of data. Cell arrays are better than structures for applications where

As an example of accessing multiple fields with one statement, assume that your data consists of

For many applications, the best data construct for this data is a structure. However, if you routinely access only the first two fields of information, then a cell array might be more convenient for indexing purposes.

This example shows how to access the first and second elements of the cell array TEST:

[newdata,name] = deal(TEST{1:2})

This example shows how to access the first and second elements of the structure TEST:

newdata = TEST.measure
name = TEST.name

The varargin and varargout arguments are examples of the utility of cell arrays as substitutes for comma-separated lists. Create a 3-by-3 numeric array A:

A = [0 1 2; 4 0 7; 3 1 2];

Now apply the normest (2-norm estimate) function to A, and assign the function output to individual cells of B:

[B{1:2}] = normest(A)
B = 
    [8.8826]    [4]

All of the output values from the function are stored in separate cells of B. B(1) contains the norm estimate; B(2) contains the iteration count.

Nesting Cell Arrays

A cell can contain another cell array, or even an array of cell arrays. (Cells that contain noncell data are called leaf cells.) You can use nested curly braces, the cell function, or direct assignment statements to create nested cell arrays. You can then access and manipulate individual cells, subarrays of cells, or cell elements.

Building Nested Arrays with Nested Curly Braces

You can nest pairs of curly braces to create a nested cell array. For example,

clear A
A(1,1) = {magic(5)};

A(1,2) = {{[5 2 8; 7 3 0; 6 7 3] 'Test 1'; [2-4i 5+7i] {17 []}}}
A = 
    [5x5 double]    {2x2 cell}

Note that the right side of the assignment is enclosed in two sets of curly braces. The first set represents cell (1,2) of cell array A. The second "packages" the 2-by-2 cell array inside the outer cell.

Building Nested Arrays with the cell Function

To nest cell arrays with the cell function, assign the output of cell to an existing cell:

  1. Create an empty 1-by-2 cell array.

    A = cell(1,2);
    
  2. Create a 2-by-2 cell array inside A(1,2).

    A(1,2) = {cell(2,2)};
    
  3. Fill A, including the nested array, using assignments.

    A(1,1) = {magic(5)};
    A{1,2}(1,1) = {[5 2 8; 7 3 0; 6 7 3]};
    A{1,2}(1,2) = {'Test 1'};
    A{1,2}(2,1) = {[2-4i 5+7i]};
    A{1,2}(2,2) = {cell(1, 2)}
    A{1,2}{2,2}(1) = {17};
    

    Note the use of curly braces until the final level of nested subscripts. This is required because you need to access cell contents to access cells within cells.

You can also build nested cell arrays with direct assignments using the statements shown in step 3 above.

Indexing Nested Cell Arrays

To index nested cells, concatenate indexing expressions. The first set of subscripts accesses the top layer of cells, and subsequent sets of parentheses access successively deeper layers.

For example, array A has three levels of nesting:

Converting Between Cell and Numeric Arrays

Use for loops to convert between cell and numeric formats. For example, create a cell array F:

F{1,1} = [1 2; 3 4];
F{1,2} = [-1 0; 0 1];
F{2,1} = [7 8; 4 1];
F{2,2} = [4i 3+2i; 1-8i 5];

Now use three for loops to copy the contents of F into a numeric array NUM:

for k = 1:4
   for m = 1:2
      for n = 1:2
         NUM(m,n,k) = F{k}(m,n);
      end
   end
end

Similarly, you must use for loops to assign each value of a numeric array to a single cell of a cell array:

G = cell(1,16);
for m = 1:16
   G{m} = NUM(m);
end

Cell Arrays of Structures

Use cell arrays to store groups of structures with different field architectures:

cStr = cell(1,2);
cStr{1}.label = '12/2/94 - 12/5/94';
cStr{1}.obs = [47 52 55 48; 17 22 35 11];
cStr{2}.xdata = [-0.03 0.41 1.98 2.12 17.11];
cStr{2}.ydata = [-3 5 18 0 9];
cStr{2}.zdata = [0.6 0.8 1 2.2 3.4];

Cell 1 of the cStr array contains a structure with two fields, one a string and the other a vector. Cell 2 contains a structure with three vector fields.

When building cell arrays of structures, you must use content indexing. Similarly, you must use content indexing to obtain the contents of structures within cells. The syntax for content indexing is

cellArray{index}.field

For example, to access the label field of the structure in cell 1, use cStr{1}.label.

Function Summary

This table describes the MATLAB functions for working with cell arrays.

Function

Description

cell

Create a cell array.

cell2struct

Convert a cell array into a structure array.

celldisp

Display cell array contents.

cellfun

Apply a cell function to a cell array.

cellplot

Display a graphical depiction of a cell array.

deal

Copy input to separate outputs.

iscell

Return true for a cell array.

num2cell

Convert a numeric array into a cell array.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS