# Create Cell Array

A cell array can store different types and sizes of data. In the past, cell arrays were recommended for text and for tabular data of different types, such as data from a spreadsheet. Now, store text data using a string array, and store tabular data using a table. Use cell arrays for heterogeneous data that is best referenced by its location within an array.

You can create a cell array in two ways: use the {} operator or use the cell function.

When you have data to put into a cell array, use the cell array construction operator {}.

C = {1,2,3;
'text',rand(5,10,2),{11; 22; 33}}
C=2×3 cell array
{[   1]}    {[          2]}    {[     3]}
{'text'}    {5x10x2 double}    {3x1 cell}

Like all MATLAB® arrays, cell arrays are rectangular, with the same number of cells in each row. C is a 2-by-3 cell array.

You also can use the {} operator to create an empty 0-by-0 cell array.

C2 = {}
C2 =

0x0 empty cell array

When you want to add values to a cell array over time or in a loop, first create an empty array using the cell function. This approach preallocates memory for the cell array header. Each cell contains an empty array [].

C3 = cell(3,4)
C3=3×4 cell array
{0x0 double}    {0x0 double}    {0x0 double}    {0x0 double}
{0x0 double}    {0x0 double}    {0x0 double}    {0x0 double}
{0x0 double}    {0x0 double}    {0x0 double}    {0x0 double}

To read from or write to specific cells, enclose indices in curly braces. For instance, populate C3 with arrays of random data. Vary the array size based on its location in the cell array.

for row = 1:3
for col = 1:4
C3{row,col} = rand(row*10,col*10);
end
end
C3
C3=3×4 cell array
{10x10 double}    {10x20 double}    {10x30 double}    {10x40 double}
{20x10 double}    {20x20 double}    {20x30 double}    {20x40 double}
{30x10 double}    {30x20 double}    {30x30 double}    {30x40 double}