Kahibaro
Discord Login Register

Cell Arrays and Cell Indexing

Introduction

Cell arrays in MATLAB provide a flexible way to store collections of data where the pieces do not all have to be the same size or the same type. They are especially useful when you want to keep related but heterogeneous information together in a single container, such as mixing numbers, strings, tables, or even other cell arrays.

In this chapter you will focus on what makes cell arrays special, how to create them, and how cell indexing works. Understanding the difference between cell indexing and content indexing is essential, because it directly affects how you access and manipulate the data stored inside cells.

What Is a Cell Array

A cell array is an array of “containers,” where each element is called a cell. Each cell can hold any MATLAB value. The overall cell array has a regular rectangular shape, like a numeric matrix, but the contents of each cell can differ in size and type.

You can imagine a cell array as a spreadsheet where each box can contain anything: a single number, a matrix, a text string, or a more complex object. The cell array itself only enforces the grid shape. What is inside each box is unconstrained.

Cell arrays are usually represented with curly braces when you construct them, but the variable itself is a regular MATLAB array with its own size, such as $1 \times 3$ or $4 \times 2$.

Creating Cell Arrays

There are several common ways to create cell arrays, depending on how much information you know at the time of creation.

Using Curly Braces Literals

The most straightforward way to create a cell array is to write a literal using curly braces. Each element between the braces becomes a cell.

For a row cell array:

matlab
C = {1, 'hello', [1 2 3]};

This creates a $1 \times 3$ cell array. The first cell holds the scalar 1, the second cell holds the character vector 'hello', and the third cell holds a numeric row vector.

For a column cell array:

matlab
C = {1; 'hello'; [1 2 3]};

Now C is a $3 \times 1$ cell array. Commas and spaces separate columns, semicolons separate rows, exactly as with numeric arrays.

You can also make multi dimensional cell arrays directly:

matlab
C = {1, 2; 'a', 'b'};

This yields a $2 \times 2$ cell array.

Using the `cell` Function

When you know the desired size but not yet the contents, you can preallocate a cell array using the cell function. This is especially useful in loops or when you intend to fill the cells later.

For example, to create an empty $2 \times 3$ cell array:

matlab
C = cell(2, 3);

At this point, each cell contains an empty array []. You can then fill the cells one by one:

matlab
C{1,1} = magic(3);
C{1,2} = 'data';
C{2,3} = pi;

You can also specify more dimensions:

matlab
C = cell(2, 2, 3);

Here C has size $2 \times 2 \times 3$, with 12 cells in total.

Converting Other Structures into Cell Arrays

Sometimes you convert existing data into a cell array. Two common approaches are:

Using num2cell to break a numeric array into cells:

matlab
A = [1 2 3; 4 5 6];
C = num2cell(A);

Now C is a $2 \times 3$ cell array, and each cell contains a single scalar taken from A. The shape of C matches the shape of A.

Using cellstr to convert character arrays into a cell array of character vectors:

matlab
names = ['Ann '; 'Bob '; 'Cia '];
C = cellstr(names);

Here C is a $3 \times 1$ cell array, each cell holding one name as a character vector without trailing spaces.

These conversions are useful when you need to treat each element or each row as a separate piece of content.

Basic Cell Indexing Concepts

Cell arrays support two main types of indexing. You must clearly distinguish between indexing the cells themselves and indexing the contents of a cell.

Parentheses () refer to cells as elements of the cell array. Curly braces {} refer to the contents stored inside particular cells.

The difference is crucial:

If you use C(1,2), you get a cell array that contains the cell at position (1,2).

If you use C{1,2}, you get the value stored inside the cell at position (1,2).

These two results often have different types and different sizes, and MATLAB will treat them differently when you use them in expressions.

Indexing Cells with Parentheses

When you use parentheses with a cell array, MATLAB returns another cell array. This is called cell indexing. It behaves similarly to indexing regular numeric arrays, but the returned values remain wrapped in cells.

For example:

matlab
C = {1, 'hello', [10 20]; pi, 42, 'world'};
subC = C(1, 2);

Here subC is a $1 \times 1$ cell array, and subC{1} is the character vector 'hello'.

Parentheses indices can select multiple cells at once:

matlab
C = {1, 2, 3, 4};
D = C(2:4);

Now D is a $1 \times 3$ cell array holding the cells from positions 2 through 4 of C.

You can also use linear indexing with a single index:

matlab
E = C(3);

In this case E is a $1 \times 1$ cell array containing the third cell of C. The notion of linear index follows the same column major order as for numeric arrays.

Using parentheses is appropriate when you want to preserve cells, for example when you want a subset of a cell array that is still a cell array.

Accessing Cell Contents with Curly Braces

Curly braces are used to access or assign the content inside a particular cell. This is called content indexing.

If C is a cell array, then C{1,2} returns the exact MATLAB value that is stored in row 1, column 2 of C. The result is not wrapped in a cell. It behaves directly as its own type.

For example:

matlab
C = {1, 'hello', [10 20]; pi, 42, 'world'};
x = C{1,1};   % x is the number 1
s = C{1,2};   % s is the character vector 'hello'
v = C{1,3};   % v is the numeric row vector [10 20]

You can also further index into the content. This is possible if the content supports indexing, for example numeric arrays or character vectors.

matlab
firstElement = C{1,3}(1);  % first element of the vector inside C{1,3}
firstChar    = C{1,2}(1);  % first character of the string 'hello'

Here, C{1,3} returns a numeric vector, and (1) then accesses the first element of that vector. Similarly, C{1,2} returns a character vector, and (1) accesses its first character.

Curly braces are required when you want to use the content directly in computations. For example:

matlab
result = C{2,2} + 10;

Assuming C{2,2} stores a number 42, result will be 52. If you wrote C(2,2) + 10 instead, MATLAB would raise an error, because it would attempt to add 10 to a cell array.

Assigning Values to Cells

You can assign values to cells with curly brace indexing. This sets the content of the cell at the specified location.

matlab
C = cell(2,2);
C{1,1} = 100;
C{1,2} = 'note';
C{2,1} = [1 2 3];
C{2,2} = magic(3);

Each assignment can place a different type or size of value into the corresponding cell. There is no requirement that all cells hold compatible types or shapes.

You can also assign values using cell indexing with parentheses, but in that case the right hand side must be a cell array. For example:

matlab
C = cell(1,3);
C(1,1:2) = {10, 20};

Here the right side {10, 20} is a $1 \times 2$ cell array, which is then assigned into the selected cells (1,1:2).

If you try to assign a non cell right side into multiple cells using parentheses, MATLAB will not allow it. This restriction helps keep the meaning of the assignment clear: parentheses work in terms of cells, curly braces work in terms of content.

Converting Between Cells and Regular Arrays

It is common to move between cell arrays and regular numeric or string arrays. The suitable method depends on how uniform the contents are.

If every cell holds a scalar of the same type, you can often convert with cell2mat:

matlab
C = {1, 2, 3; 4, 5, 6};
A = cell2mat(C);

This produces a $2 \times 3$ numeric array A. cell2mat requires that the resulting concatenation be valid as a single numeric or logical array. If the contents are incompatible in size or type, it will produce an error.

If each cell contains a character vector, you may use string or char depending on whether you want a string array or a character array:

matlab
C = {'apple', 'banana', 'cherry'};
S = string(C);   % string array of size 1x3

In many situations, accessing the content directly with curly braces is enough, and no full conversion is needed. For example, to sum numeric contents:

matlab
C = {1, 2, 3};
total = C{1} + C{2} + C{3};

For larger cell arrays, it is common to use helper functions that work over cell contents, but the details of such operations belong to more advanced usage.

Linear Indexing of Cell Arrays

Cell arrays support linear indexing just like other MATLAB arrays. You can refer to cells using a single index that runs through the array column by column.

Using parentheses with a single index returns cells:

matlab
C = {1, 2; 3, 4};
cellAt3 = C(3);   % 3rd cell in column major order

Here cellAt3 is a $1 \times 1$ cell array whose content is 3.

Using curly braces with a single index returns content:

matlab
valueAt3 = C{3};  % numeric value 3

This can be convenient when you want to iterate through all cells without tracking row and column coordinates. You simply increase the linear index or use it inside loops.

Working with Multiple Cell Contents

Cell arrays allow you to operate on multiple contents at once by using comma separated lists. When you use curly braces with multiple indices on the left side of an assignment, MATLAB produces a comma separated list of contents. This can be unpacked into multiple output variables.

For example:

matlab
C = {10, 20, 30};
[a, b, c] = C{:};

Here C{:} produces a comma separated list 10, 20, 30, and these are assigned to a, b, and c respectively. As a result, a is 10, b is 20, and c is 30.

You can also assign back into cells:

matlab
[a, b] = deal(1, 2);
C = cell(1,2);
[C{1}, C{2}] = deal(a, b);

In this case C{1} receives the value of a, and C{2} receives the value of b.

This technique is useful when you want to capture several cell contents at once, or when you want to redistribute values into different cells in one operation.

Editing the Shape of Cell Arrays

Cell arrays can be resized or reshaped using standard array operations, but you must preserve the total number of cells. The structure of the contents inside each cell is independent of the shape of the outer cell array.

For example, you can reshape a $1 \times 4$ cell array into a $2 \times 2$ cell array:

matlab
C = {1, 2, 3, 4};
D = reshape(C, 2, 2);

Now D{1,1} is 1, D{2,1} is 2, D{1,2} is 3, and D{2,2} is 4, following column major order. The cells retain their contents; only their positions in the grid change.

You can also grow a cell array by assigning to indices outside its current bounds, just as with other arrays:

matlab
C = {1, 2};
C{1,3} = 3;     % C becomes 1x3
C{2,1} = 10;    % C becomes 2x3

Newly created cells that you do not explicitly assign get filled with empty arrays [].

Common Pitfalls with Cell Indexing

A frequent source of confusion is using () instead of {} or the other way around. Mixing them incorrectly often causes type errors or unexpected behavior.

If you forget to use curly braces when you need the content, you may end up passing a cell where a numeric or string value is required. For example:

matlab
C = {1, 2, 3};
sum(C);      % error, sum does not accept a cell array like this
sum([C{:}]); % valid, content is extracted then concatenated

Another mistake is attempting to index inside content while still using parentheses on the cell array. For example:

matlab
C = {1, [10 20 30]};
x = C(2)(1);  % incorrect, you cannot chain () like this on a cell

MATLAB cannot interpret C(2)(1) in this context. The correct way is:

matlab
x = C{2}(1);  % extract second cell content, then index it

Always remember that () operates at the level of cells, and {} reaches inside to the actual stored values.

Important points to remember:

  1. () selects cells and returns cell arrays. {} selects contents and returns regular MATLAB values.
  2. Use {} when you want to perform computations on the stored data. Use () when you want to keep or manipulate subsets of the cell array itself.
  3. Assign content to individual cells with {}. Assign cell arrays to multiple cells with ().
  4. Many functions do not accept cell arrays directly. You often need to extract content with {} or convert with functions like cell2mat before using them.

Views: 4

Comments

Please login to add a comment.

Don't have an account? Register now!