Tutorial

Cell Arrays and Content Indexing in MATLAB

Content indexing allows to reference the content of cells in a cell array.

Preparation

Create a cell array using the following code:

A = {'Peter Pan', 'M', 11; 'Wendy Darling', 'F', 12};

Content indexing

Enclose linear, subscript or logical indices in curly braces to refer to the content of cells in a cell array.

% Content of the first cell
name = A{1};
whos name;
% Content of the cells in the first column
[name1,name2] = A{1:2};
% Write the content of the first cell
A{1} = 'Peter';
% Write the content of the cells in the second column
newValues = {'Male','Female'};
[A{3:4}] = newValues{:};
% Wrong code
A{3:4} = {'Male','Female'};

Table 1 summarizes how content indexing works in read and write operations.

Table 1. Use cases of content indexing.
Case Description
Read a single cell The content of the cell is returned “as-is”
Read a set of cells The content of the cells is returned as a comma-separated list
Write a single cell The right part of the assignment can be anything
Write a set of cells The right part of the assignment must generate a comma-separated list

Further reading

I recommend the following books to learn more on cell arrays and content indexing in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. Cell arrays, and other data types, are explained clearly in the eighth chapter.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Chapter 11 explains excellently cell arrays, structure arrays, and character arrays, among other data types.

I also recommend the other tutorials in this series.

Source code

I hope you have understood how content indexing works in MATLAB. The source code developed in this tutorial is available at this page.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.