Skip to Main Content Skip to Search
Product Documentation

Cell Arrays

What Is a Cell Array?

A cell array is a data type with indexed data containers called cells. Each cell can contain any type of data. Cell arrays commonly contain lists of text strings, combinations of text and numbers from spreadsheets or text files, or numeric arrays of different sizes.

There are two ways to refer to the elements of a cell array. Enclose indices in smooth parentheses, (), to refer to sets of cells — for example, to define a subset of the array. Enclose indices in curly braces, {}, to refer to the text, numbers, or other data within individual cells.

For more information, see:

Create a Cell Array

This example shows how to create a cell array using the {} operator or the cell function.

When you have data to put into a cell array, create the array using the cell array construction operator, {}:

myCell = {1, 2, 3;
          'text', rand(5,10,2), {11; 22; 33}}

Like all MATLAB arrays, cell arrays are rectangular, with the same number of cells in each row. myCell is a 2-by-3 cell array:

myCell = 
    [   1]    [            2]    [       3]
    'text'    [5x10x2 double]    {3x1 cell}

You also can use the {} operator to create an empty 0-by-0 cell array,

C = {}

If you plan to add values to a cell array over time or in a loop, you can create an empty n-dimensional array using the cell function:

emptyCell = cell(3,4,2)

emptyCell is a 3-by-4-by-2 cell array, where each cell contains an empty array, []:

emptyCell(:,:,1) = 
    []    []    []    []
    []    []    []    []
    []    []    []    []

emptyCell(:,:,2) = 

    []    []    []    []
    []    []    []    []
    []    []    []    []

For more information, see:

Access Data in a Cell Array

This example shows how to read and write data to and from a cell array. To run the code in this example, create a 2-by-3 cell array of text and numeric data:

C = {'one', 'two', 'three';
     1, 2, 3};

There are two ways to refer to the elements of a cell array. Enclose indices in smooth parentheses, (), to refer to sets of cells—for example, to define a subset of the array. Enclose indices in curly braces, {}, to refer to the text, numbers, or other data within individual cells.

Cell Indexing with Smooth Parentheses, ()

Cell array indices in smooth parentheses refer to sets of cells. For example, the command

upperLeft = C(1:2,1:2)

creates a 2-by-2 cell array:

upperLeft = 
    'one'    'two'
    [  1]    [  2]

Update sets of cells by replacing them with the same number of cells. For example, the statement

C(1,1:3) = {'first','second','third'}

replaces the cells in the first row of C with an equivalent-sized (1-by-3) cell array:

C = 
    'first'    'second'    'third'
    [    1]    [     2]    [    3]

If cells in your array contain numeric data, you can convert the cells to a numeric array using the cell2mat function:

numericCells = C(2,1:3)
numericVector = cell2mat(numericCells)

numericCells is a 1-by-3 cell array, but numericVector is a 1-by-3 array of type double:

numericCells = 
    [1]    [2]    [3]

numericVector =
     1     2     3

Content Indexing with Curly Braces, {}

Access the contents of cells—the numbers, text, or other data within the cells—by indexing with curly braces. For example, the command

last = C{2,3}

creates a numeric variable of type double, because the cell contains a double value:

last =
     3

Similarly, this command

C{2,3} = 300

replaces the contents of the last cell of C with a new, numeric value:

C = 
    'first'    'second'    'third'
    [    1]    [     2]    [  300]

When you access the contents of multiple cells, such as

C{1:2,1:2}

MATLAB creates a comma-separated list. Because each cell can contain a different type of data, you cannot assign this list to a single variable. However, you can assign the list to the same number of variables as cells. MATLAB assigns to the variables in column order. For example,

[r1c1, r2c1, r1c2, r2c2] = C{1:2,1:2}

returns

r1c1 =
     first

r2c1 =
     1

r1c2 =
     second

r2c2 =
     2

If each cell contains the same type of data, you can create a single variable by applying the array concatenation operator, [], to the comma-separated list. For example,

nums = [C{2,:}]

returns

nums =
     1     2   300

For more information, see:

Add Cells to a Cell Array

This example shows how to add cells to a cell array.

Create a 1-by-3 cell array:

C = {1, 2, 3};

Assign data to a cell outside the current dimensions:

C{4,4} = 44

MATLAB expands the cell array to a rectangle that includes the specified subscripts. Any intervening cells contain empty arrays:

C = 
    [1]    [2]    [3]      []
     []     []     []      []
     []     []     []      []
     []     []     []    [44]

Add cells without specifying a value by assigning an empty array as the contents of a cell:

C{5,5} = []

C is now a 5-by-5 cell array:

C = 
    [1]    [2]    [3]      []    []
     []     []     []      []    []
     []     []     []      []    []
     []     []     []    [44]    []
     []     []     []      []    []

For related examples, see:

Delete Data from a Cell Array

This example shows how to remove data from individual cells, and how to delete entire cells from a cell array. To run the code in this example, create a 3-by-3 cell array:

C = {1, 2, 3; 4, 5, 6; 7, 8, 9};

Delete the contents of a particular cell by assigning an empty array to the cell, using curly braces for content indexing, {}:

C{2,2} = []

This code returns

C = 
    [1]    [2]    [3]
    [4]     []    [6]
    [7]    [8]    [9]

Delete sets of cells using standard array indexing with smooth parentheses, (). For example, this command

C(2,:) = []

removes the second row of C:

C = 
    [1]    [2]    [3]
    [7]    [8]    [9]

For related examples, see:

Combine Cell Arrays

This example shows how to combine cell arrays by concatenation or nesting. To run the code in this example, create several cell arrays with the same number of columns:

C1 = {1, 2, 3};
C2 = {'A', 'B', 'C'};
C3 = {10, 20, 30};

Concatenate cell arrays with the array concatenation operator, []. In this example, vertically concatenate the cell arrays by separating them with semicolons:

C4 = [C1; C2; C3]

C4 is a 3-by-3 cell array:

C4 = 
    [ 1]    [ 2]    [ 3]
    'A'     'B'     'C' 
    [10]    [20]    [30]

Create a nested cell array with the cell array construction operator, {}:

C5 = {C1; C2; C3}

C5 is a 3-by-1 cell array, where each cell contains a cell array:

C5 = 
    {1x3 cell}
    {1x3 cell}
    {1x3 cell}

For more information, see Concatenating Matrices.

Pass Contents of Cell Arrays to Functions

These examples show several ways to pass data from a cell array to a MATLAB function that does not recognize cell arrays as inputs.

For more information, see:

Preallocate Memory for a Cell Array

This example shows how to initialize and allocate memory for a cell array.

Cell arrays do not require completely contiguous memory. However, each cell requires contiguous memory, as does the cell array header that MATLAB creates to describe the array. For very large arrays, incrementally increasing the number of cells or the number of elements in a cell results in Out of Memory errors.

Initialize a cell array by calling the cell function, or by assigning to the last element. For example, these statements are equivalent:

C = cell(25,50);
C{25,50} = [];

MATLAB creates the header for a 25-by-50 cell array. However, MATLAB does not allocate any memory for the contents of each cell.

For more information, see:

Cell vs. Struct Arrays

This example compares cell and structure arrays, and shows how to store data in each type of array. Both cell and structure arrays allow you to store data of different types and sizes.

Structure Arrays

Structure arrays contain data in fields that you access by name.

For example, store patient records in a structure array.

patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];

patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];

Create a bar graph of the test results for each patient.

numPatients = numel(patient);
for p = 1:numPatients
   figure
   bar(patient(p).test)
   title(patient(p).name)
end

Cell Arrays

Cell arrays contain data in cells that you access by numeric indexing. Common applications of cell arrays include storing lists of text strings and storing heterogeneous data from spreadsheets.

For example, store temperature data for three cities over time in a cell array.

temperature(1,:) = {'01-Jan-2010', [45, 49, 0]};
temperature(2,:) = {'03-Apr-2010', [54, 68, 21]};
temperature(3,:) = {'20-Jun-2010', [72, 85, 53]};
temperature(4,:) = {'15-Sep-2010', [63, 81, 56]};
temperature(5,:) = {'31-Dec-2010', [38, 54, 18]};

Plot the temperatures for each city by date.

allTemps = cell2mat(temperature(:,2));
dates = datenum(temperature(:,1), 'dd-mmm-yyyy');

plot(dates,allTemps)
datetick('x','mmm')

Other Container Arrays

Struct and cell arrays are the most commonly used containers for storing heterogeneous data. If you have installed the Statistics Toolbox™, you can also use dataset arrays. Alternatively, use map containers, or create your own class.

Related Topics

Multilevel Indexing to Access Parts of Cells

This example explains techniques for accessing data in arrays stored within cells of cell arrays. To run the code in this example, create a sample cell array:

myNum = [1, 2, 3];
myCell = {'one', 'two'};
myStruct.Field1 = ones(3);
myStruct.Field2 = 5*ones(5);

C = {myNum, 100*myNum;
     myCell, myStruct};

Access the complete contents of a particular cell using curly braces, {}. For example,

C{1,2}

returns the numeric vector from that cell:

ans =
   100   200   300

Access part of the contents of a cell by appending indices, using syntax that matches the data type of the contents. For example:

You can nest any number of cell and structure arrays. For example, add nested cells and structures to C.

C{2,1}{2,2} = {pi, eps};
C{2,2}.Field3 = struct('NestedField1', rand(3), ...
                       'NestedField2', magic(4), ...
                       'NestedField3', {{'text'; 'more text'}} );

These assignment statements access parts of the new data:

copy_pi = C{2,1}{2,2}{1,1}

part_magic = C{2,2}.Field3.NestedField2(1:2,1:2)

nested_cell = C{2,2}.Field3.NestedField3{2,1}

MATLAB displays:

copy_pi =
    3.1416

part_magic =
    16     2
     5    11

nested_cell =
    more text
  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

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