Cell Arrays
A regular array holds elements of one type and every row must have the same length. A cell array lifts both restrictions: each cell can hold anything (a number, a char array of any length, a matrix, even another cell array). Cell arrays are created with curly braces.
info = {'Ada Lovelace', 1815, [3 1 4 1 5], true}
disp(class(info))
disp(size(info))info =
{
[1,1] = Ada Lovelace
[1,2] = 1815
[1,3] =
3 1 4 1 5
[1,4] = 1
}
cell
1 4
(MATLAB displays cell arrays more compactly, as {'Ada Lovelace'} {[1815]} {1x5 double} {[1]}.)
Two kinds of indexing
This is the single most important idea about cell arrays:
- Curly braces
c{k}give you the contents of a cell. - Parentheses
c(k)give you a smaller cell array containing that cell.
info = {'Ada Lovelace', 1815, [3 1 4 1 5]};
name = info{1};
disp(class(name)) % char: the contents
sub = info(1);
disp(class(sub)) % cell: still wrapped
disp(info{2} + 10) % arithmetic needs the contents
disp(info{3}(2)) % index into the vector inside cell 3char
cell
1825
1
Think of a cell array as a row of labelled boxes: () hands you boxes, {} opens them.
Creating and growing
Preallocate an empty cell array with cell(m, n), then fill it with curly-brace assignment. Assigning past the end grows the array:
c = cell(1, 3);
disp(isempty(c{2}))
c{1} = 'alpha';
c{2} = 42;
c{3} = magic(3);
c{5} = 'five'; % cell 4 is created empty
disp(numel(c))
disp(isempty(c{4}))
c(2) = []; % parentheses + [] deletes a cell
disp(numel(c))1
5
1
4
Cell arrays of text
The most common use: a list of names, labels or words of different lengths. Many text functions (upper, strcat, strcmp, regexprep, strjoin, …) accept cell arrays directly:
cities = {'Oslo', 'Lisbon', 'Kyoto', 'Lima'};
fprintf('%s\n', cities{:});
disp(strjoin(upper(cities), ', '))
disp(strcmp(cities, 'Kyoto'))
[sortedCities, order] = sort(cities);
disp(strjoin(sortedCities, ' < '))
disp(order)
lens = cellfun(@length, cities)Oslo
Lisbon
Kyoto
Lima
OSLO, LISBON, KYOTO, LIMA
0 0 1 0
Kyoto < Lima < Lisbon < Oslo
3 4 2 1
lens =
4 6 5 4
cities{:} expands to a comma-separated list of all the contents, which is exactly what fprintf wants as separate arguments. sort works alphabetically on a cell array of text, and cellfun applies a function to every cell (more in the arrayfun & cellfun lesson).
Comma-separated lists
The c{:} expansion is useful in other places too: building a vector from cells, passing options to a function, or assigning several outputs at once with deal:
nums = {4, 8, 15};
v = [nums{:}] % concatenate the contents
args = {'%s scored %d\n', 'Mia', 91};
fprintf(args{:});
[a, b] = deal('first', 'second');
fprintf('%s, %s\n', a, b);v =
4 8 15
Mia scored 91
first, second
Converting
| Function | Converts |
|---|---|
num2cell(A) |
Each element of an array into its own cell |
cell2mat(c) |
A cell array of compatible arrays into one array |
iscellstr(c) |
Tests whether every cell holds a char array |
cellfun(@isempty, c) |
Logical array: which cells are empty |
c = num2cell([1 2 3]);
disp(size(c))
m = cell2mat({[1 2], [3]; [4 5], [6]});
disp(m)
disp(iscellstr({'a', 'bc'}))
disp(iscellstr({'a', 5}))
mixed = {'x', [], 'y', ''};
disp(cellfun(@isempty, mixed)) 1 3
1 2 3
4 5 6
1
0
0 1 0 1
When to use a cell array
- A list of texts of different lengths.
- Grouping values of different types (but if they have names, a structure is clearer).
- Collecting results of different sizes in a loop.
- Passing a variable number of arguments to functions (
varargin, covered later).
For numeric data of a single type, stay with a normal array: it's faster and works with all the math functions.
Test yourself
For c = {10, 'hi'}, what is class(c(1))?
doublecellcharstruct
What does [c{:}] do for c = {1, 2, 3}?
- Returns the cell array unchanged
- Concatenates the contents into
[1 2 3] - Raises an error
- Returns the number of cells
How do you create an empty 2x3 cell array?
zeros(2, 3)cell(2, 3){}(2, 3)cellarray(2, 3)