Create Cell Array - MATLAB & Simulink (original) (raw)

Main Content

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'} {5×10×2 double} {3×1 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 =

0×0 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=3×4 cell array {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 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(row10,col10); end end C3

C3=3×4 cell array {10×10 double} {10×20 double} {10×30 double} {10×40 double} {20×10 double} {20×20 double} {20×30 double} {20×40 double} {30×10 double} {30×20 double} {30×30 double} {30×40 double}

See Also

cell

Topics