BudiBadu Logo
Samplebadu

MATLAB by Example: Cell Arrays

R2023b

Cell arrays are containers that can hold data of different types and sizes. This example demonstrates curly brace indexing.

Code

% Creating a cell array with curly braces
myCell = {'Text', [1 2; 3 4], 100};

% Accessing the content of a cell (curly braces)
str = myCell{1};      % Returns the string 'Text'
mat = myCell{2};      % Returns the 2x2 matrix

% Accessing the cell container itself (parentheses)
c = myCell(1);        % Returns a 1x1 cell array containing 'Text'

% Cell arrays for strings (legacy, but common)
names = {'Alice', 'Bob', 'Charlie'};

% Mixed types
data = cell(2, 2);
data{1, 1} = 'Name';
data{1, 2} = 'Age';
data{2, 1} = 'John';
data{2, 2} = 30;

Explanation

Standard MATLAB matrices must contain data of the same type (e.g., all doubles). Cell arrays overcome this limitation. A cell array is a data type that can hold data of varying types and sizes in its elements. You create them using curly braces {} or the cell function.

There are two ways to index into a cell array, and the distinction is critical. Using parentheses (), like myCell(1), returns a subset of the cell array (i.e., another cell array). Using curly braces {}, like myCell{1}, extracts the content of the cell. Think of the cell as a box: parentheses give you the box, curly braces give you what's inside the box.

Cell arrays are frequently used for storing lists of text strings (though string arrays are now preferred in modern MATLAB) or for creating heterogeneous datasets where rows might contain a mix of names, dates, and numerical values.

Code Breakdown

2
{'Text', ...} creates the cell array. Note the mixed types: string, matrix, number.
5
myCell{1} uses content indexing to get the actual string 'Text'.