0
0
MATLABdata~5 mins

Cell array creation in MATLAB

Choose your learning style9 modes available
Introduction

Cell arrays let you store different types of data together in one container. They are useful when you want to keep numbers, text, or other data mixed in one place.

You want to store a list of names and ages together.
You need to keep different types of data like strings and numbers in one variable.
You want to group results from different calculations that have different data types.
You want to create a flexible container that can hold arrays of different sizes or types.
Syntax
MATLAB
cellArray = {item1, item2, item3, ...};

Use curly braces { } to create a cell array.

Each item inside can be any data type: number, string, array, or even another cell array.

Examples
This creates a cell array with a number, a string, and a numeric array.
MATLAB
myCell = {42, 'hello', [1, 2, 3]};
This creates an empty cell array with no elements.
MATLAB
emptyCell = {};
This creates a cell array with just one element, the number 99.
MATLAB
singleCell = {99};
This creates a cell array where the second element is another cell array.
MATLAB
nestedCell = { 'text', {1, 2, 3} };
Sample Program

This program creates a cell array with a number, a string, and a numeric array. It then prints the whole cell array and each element separately.

MATLAB
clc;
clear;

% Create a cell array with different types of data
mixedCell = {123, 'MATLAB', [10, 20, 30]};

% Display the whole cell array
disp('Original cell array:');
disp(mixedCell);

% Access and display each element separately
for index = 1:length(mixedCell)
    fprintf('Element %d: ', index);
    disp(mixedCell{index});
end
OutputSuccess
Important Notes

Creating a cell array is fast and uses space proportional to the number of elements.

Access elements with curly braces { } to get the content, or parentheses ( ) to get a sub-cell array.

Common mistake: Using parentheses instead of curly braces to access data inside cells returns a cell, not the data itself.

Use cell arrays when you need to store mixed data types; use regular arrays when all data is the same type.

Summary

Cell arrays hold different types of data together.

Use curly braces { } to create and access cell contents.

They are useful for flexible, mixed-type collections.