Tutorial

How to Create Cell Arrays in MATLAB

A cell array is a data type that uses indexed containers called “cells” to store data of varying types and sizes.

cell function

Use the cell function to preallocate a cell array of a certain size. Each cell is initialized to an empty array of type double.

% 2-by-3 cell array
resultExample1 = cell(2,3);

Recommendation: Use cell to avoid the continuous resizing of cell arrays during loops, which hurts performance. Preallocate the entire cell array outside the loop, and in the loop set the content of each cell.

{} operator

Use the cell array construction operator (i.e. {}) when you have data to put into a new cell array. Cell arrays can have any dimensions, but this operator only creates 2D cell arrays.

Inside {}, use a comma to separate elements of the same row, and a semicolon to separate rows.
% 1-by-3 cell array
resultExample2 = {'Peter Pan', 'M', 11};
% 2-by-3 cell array
resultExample3 = {'Peter Pan', 'M', 11; 'Wendy Darling', 'F', 12};

Further reading

I recommend the following books to learn more on cell arrays 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 following page in the help documentation, and the other tutorials in this series.

doc cell;

Exercise

A Minimum Bounding Box (MBR) is the minimum rectangle that encloses a group of pixels. MBRs are usually defined by the location of the upper-left corner, a width, and a height.

Store in a cell array the MBRs specified in Table 1. Cell array rows must correspond to table rows.

Table 1. Listing of minimum bounding boxes.
label xorigin yorigin width height
MBR1 0 0 10 5
MBR2 10 5 7 8
MBR3 7 9 3 6

Source code

I hope you have learned how to create cell arrays 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.