Skip to content

MATLAB - Cell Arrays

A cell array is a fundamental MATLAB data type that acts as a flexible container. Unlike standard numeric arrays which must hold elements of the same type (e.g., all double or all char), a cell array can store a collection of items of different types and sizes in its individual cells.

Think of a regular array as a carton of eggs (all elements are the same), whereas a cell array is a bento box or a tackle box, where each compartment can hold something completely different: a number, a piece of text, another array, or even another cell array.

While powerful, cell arrays are not always the best choice. Modern MATLAB offers specialized data types that are often more efficient and convenient. Here’s a quick guide on when to use what:

Data TypeBest ForExample
Numeric ArrayHomogeneous numerical data (matrices, vectors). All mathematical operations.[1, 2, 3; 4, 5, 6]
String ArrayHomogeneous text data. Provides rich functions for text manipulation.["Apple", "Banana", "Cherry"]
TableHeterogeneous but structured (columnar) data, like a spreadsheet. Columns can have different types but are all the same length.table(Name, Age, Score)
StructStoring a collection of different data types under named fields, representing a single object.patient.name = "John"; patient.age = 45;
Cell ArrayStoring unstructured or jagged collections of heterogeneous data. Often used for function outputs with varying sizes or types.{'Hello', [1 2; 3 4], magic(5)}

You can create cell arrays using curly braces {} for direct construction or the cell() function for pre-allocation.

Use curly braces {} to enclose your collection of data. Use semicolons ; to start new rows.

% A 1x3 cell array
myCells = { 'This is a character array', [10 20 30], true };
% A 2x2 cell array
dataLog = { "Experiment A", [1.5, 2.3, 2.1]; ...
"Experiment B", [0.8, 0.9, 0.85] };
disp(dataLog);

This is the most common point of confusion for new MATLAB users. Understanding the difference between parenthesis and curly braces for indexing is key.

  • Parentheses (): Access the Cell (the container). This returns a new cell array containing the specified cells. It’s like taking a compartment out of the bento box but keeping it closed.
  • Curly Braces {}: Access the Content (what’s inside). This extracts the actual data from within the cell. It’s like opening the compartment and taking the food out.
dataLog = { "Experiment A", [1.5, 2.3, 2.1]; ...
"Experiment B", [0.8, 0.9, 0.85] };
% --- Using Parentheses () ---
cellSubset = dataLog(1, :); % Gets the first row
disp('Using (): Returns a 1x2 cell array')
disp(cellSubset);
% You CANNOT perform math on cellSubset, e.g., cellSubset(1,2) + 1 -> ERROR
% --- Using Curly Braces {} ---
content = dataLog{1, 2}; % Extracts the content of the cell at (1,2)
disp('Using {}: Returns the numeric vector inside the cell')
disp(content);
% You CAN perform math on the content
meanValue = mean(content);
disp(['Mean of data: ', num2str(meanValue)]);

For performance, especially in loops, it’s a best practice to pre-allocate memory for your array. The cell() function creates a cell array of a specified size, filled with empty matrices.

% Pre-allocate a 10x3 cell array
results = cell(10, 3);
% Populate the array in a loop
for i = 1:10
results{i, 1} = sprintf("Run %d", i); % Content for col 1: a string
results{i, 2} = rand(1, i); % Content for col 2: a random vector of changing size
results{i, 3} = rand() > 0.5; % Content for col 3: a logical value
end
disp('First 3 rows of pre-allocated cell array:');
disp(results(1:3, :));

MATLAB provides functions to convert other data types into cell arrays, which can be useful for compatibility with older functions or for specific data manipulation tasks.

Converts a numeric array into a cell array. Each element of the numeric array becomes the content of a cell.

numericMatrix = [1 2; 3 4];
cellMatrix = num2cell(numericMatrix);
% cellMatrix is now a 2x2 cell array where cellMatrix{1,1} contains 1, etc.

Converts a table into a cell array. Use this with caution. Converting a table to a cell array loses the valuable column names and metadata. It’s generally better to work with tables directly. This conversion is mainly for interfacing with older functions that do not accept tables as input.

% Create a modern table
Name = ["Riya"; "Siya"; "Tiya"];
Age = [25; 30; 28];
Height = [160; 175; 168];
Weight = [55; 70; 65];
dataTable = table(Name, Age, Height, Weight);
% Convert to a cell array (losing column names)
cellData = table2cell(dataTable);
disp('Original Table:');
disp(dataTable);
disp('Converted Cell Array:');
disp(cellData);
  • Indexing Confusion: The most common error is mixing up () and {}. If you get an error like “Undefined function ‘plus’ for input arguments of type ‘cell’”, you probably used () when you needed {}.
  • Performance: MATLAB arrays grow dynamically, but it’s inefficient. Always pre-allocate with cell(rows, cols) before filling a cell array in a loop.
  • Choose the Right Tool: Don’t default to cell arrays. If your data is tabular, use a table. If it’s a list of strings, use a string array. Use cell arrays for truly unstructured, mixed data.