Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 45 ยท Data Types and Text

Cell Arrays

Learn MATLAB and Octave cell arrays: braces versus parentheses, creating and indexing cells, cellfun, cell2mat, mixed data and comma-separated lists.

A normal matrix holds numbers of one type, and every row must have the same length. Real data is rarely that tidy. You might want to keep three names of different lengths, or a number next to a text label next to a small matrix. A cell array is the container for that. It is a matrix whose elements are cells, and each cell can hold anything: a number, text, a matrix, even another cell array.

Cells show up constantly: strsplit returns one, cellfun processes one, and functions with variable numbers of inputs (varargin) receive one. The key skill is knowing the difference between the two kinds of brackets used with them, which is the topic of most confusion for beginners.

MATLAB and Octave blocks here are read-only. The runnable examples are Python stand-ins that use lists to mimic cell behavior, and they say which MATLAB feature they correspond to.

Two brackets, two meanings

c(2) Parentheses give you a cell, the box itself.
c{2} Braces give you the contents, what is inside.

Braces open the box. Parentheses carry the box.

1 / 2

Creating cell arrays

Curly braces build a cell array. Separate elements with spaces or commas for a row, and with semicolons for a new row:

MATLAB
c = {42, 'hello', [1 2 3]}
% c =
%   1x3 cell array
%     {[42]}    {'hello'}    {[1x3 double]}

names = {'Ada'; 'Grace'; 'Katherine'};   % 3x1 cell of text
size(names)                              % 3 1
empty = cell(2, 3);                      % 2x3 cell, every cell is []
class(c)                                 % 'cell'

The display shows each cell's summary, not its full contents: a matrix appears as [1x3 double]. Use cell(m, n) to preallocate and fill the cells later, which is faster than growing the array one element at a time.

Parentheses versus braces

This is the rule to memorize. Imagine every cell as a small box on a shelf.

  • c(2) uses parentheses and returns a 1-by-1 cell array: the shelf with one box on it.
  • c{2} uses braces and returns the contents: whatever is inside that box.
MATLAB
c = {42, 'hello', [1 2 3]};
a = c(2);       % a is a 1x1 cell:  {'hello'}
b = c{2};       % b is the text:    'hello'
class(a)        % 'cell'
class(b)        % 'char'
c{3}(2)         % 2   (brace to open the box, then index into the matrix)

Parentheses are useful when you want a subset of the array as another cell array, for example c(1:2). Braces are what you use when you want to work with the data. Trying c{2} + 1 on a text cell treats the characters as numbers; trying c(1) + 1 fails with an error about binary operators on cell arrays.

You change cells the same way. c{2} = 'bye' replaces the contents of cell 2, and c(2) = [] deletes cell 2 entirely, shrinking the array.

Python Box versus contents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python's slice c[1:2] returns a list (the box) and c[1] returns the item, so the analogy fits closely. Remember that MATLAB counts from 1 and Python from 0, so the stand-in uses index 1 where MATLAB uses 2.

Indexing and growing

All the usual matrix indexing works on the cell array itself. Use parentheses for ranges and braces for single items:

MATLAB
words = {'red', 'green', 'blue', 'cyan'};
words(2:3)          % {'green', 'blue'}   (a 1x2 cell)
words{end}          % 'cyan'
words{5} = 'pink';  % grows to 1x5
numel(words)        % 5

Assigning past the end grows the array, filling the gap with empty cells. As with numeric arrays, growing inside a long loop is slow; see Performance and Memory for preallocation advice.

Applying a function to every cell

You cannot call numel(words) and expect lengths of each word, because that counts the cells. cellfun applies a function to each cell's contents:

MATLAB
words = {'red', 'green', 'blue', 'cyan'};
lens = cellfun(@numel, words)
% lens = 3 5 4 4
upper_words = cellfun(@upper, words, 'UniformOutput', false)
% upper_words = {'RED', 'GREEN', 'BLUE', 'CYAN'}
hasE = cellfun(@(w) any(w == 'e'), words)
% hasE = 1 1 1 0

When every call returns one number, cellfun gathers them into an ordinary array. When results have different sizes (text, vectors), add 'UniformOutput', false and you get another cell array. Function handles such as @numel and the anonymous @(w) ... form are covered in Anonymous Functions and Function Handles.

Python cellfun with list comprehensions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The list comprehension is the idiomatic Python version of cellfun. The last line is a common MATLAB use of cellfun: asking every cell for its class.

Turning cells into matrices

cell2mat stitches the contents of a cell array into one ordinary matrix, as long as the pieces have compatible sizes and the same type. num2cell goes the other way and puts each element of a matrix in its own cell:

MATLAB
parts = {[1 2], [3 4 5]};
cell2mat(parts)            % [1 2 3 4 5]
grid = {[1 2], [3]; [4 5], [6]};
cell2mat(grid)             % [1 2 3; 4 5 6]
num2cell([10 20 30])       % {10, 20, 30}

If the pieces do not fit together (for example, joining a 1-by-2 and a 2-by-1), cell2mat stops with a dimension error. The function is also unhappy with mixed types such as a number next to text, so keep cell arrays of numbers separate from cell arrays of text.

Comma-separated lists

Using braces on several cells produces a comma-separated list, as if you had typed the values one by one. That list can feed a matrix constructor, a function call or another cell:

MATLAB
c = {1, 2, 3};
v = [c{:}]              % [1 2 3]
a = {c{:}, 4}           % {1, 2, 3, 4}
[c{1:2}] = deal(0)      % sets the first two cells to 0

[c{:}] is how you flatten a cell of numbers, and vertcat(c{:}) stacks cells of row vectors into a matrix. Functions with varargin receive their extra inputs in a cell, and calling f(args{:}) passes them back out as separate arguments.

Python Comma-separated list idioms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python's *args is the direct counterpart of args{:}: both spread a container into separate arguments.

When to choose cells

Cells are the right tool for text of different lengths, results of different shapes and function arguments of different kinds. If all items are numbers of the same size, a plain matrix is faster and shorter. If you need named parts, such as a person with a name, an age and a list of scores, use a structure instead, because p.name is far clearer than p{1}.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. If c = {10, 'x'}, what does c{2} return?

    Braces return the contents of the cell, here the character 'x'. Parentheses, c(2), would return a 1x1 cell.
  2. 2. What does cellfun(@numel, {'ab', 'cde', ''}) return?

    Each call returns one number, so cellfun collects them into a regular numeric array. The empty text has 0 elements.
  3. 3. Which option is needed when cellfun returns something that is not a single number per cell, such as upper-cased text?

    With 'UniformOutput', false the results are returned in a cell array, which can hold items of any size.
  4. 4. What does c(2) = [] do to a cell array c?

    Assigning [] with parentheses removes the element. To empty a cell but keep its place, use c{2} = [].

Summary

  • A cell array holds items of any type or size; create it with { } or cell(m, n).
  • Parentheses return a cell (the box); braces return its contents.
  • cellfun applies a function to every cell; use 'UniformOutput', false for non-scalar results.
  • cell2mat and num2cell convert between cells and matrices; [c{:}] flattens a cell of numbers.
  • Braces on several cells give a comma-separated list, the counterpart of Python's *args.

Next: Structures, where you'll give each piece of data a name.