Pre-allocation of Cell Arrays

67 views (last 30 days)
MiauMiau on 24 Mar 2014
Edited: Matt J on 24 Mar 2014
I have two questions regarding the pre-allocation of cell arrays. The online documentation says the following:
"Incrementally increasing the number of cells or the number of elements in a cell results in Out of Memory errors."
So, this is the same as for matrices, where e.g. one should pre-allocate for a for loop which fills a matrix a zero matrix of the required size. But then:
"Cell arrays do not require completely contiguous memory."
What does that mean exactly, i.e. where is the difference nevertheless?
"However, each cell requires contiguous memory" - and what is that supposed to mean? I mean it is not possible to allocate fragmented memory for each cell of a cell array, right?

Accepted Answer

Matt J
Matt J on 24 Mar 2014
Edited: Matt J on 24 Mar 2014
Basically, numeric matrix data types in MATLAB are allocated non-fragmented memory. As you move along columns in a matrix, you traverse adjacent memory locations.
The different elements of a cell array, however, can hold matrices or other objects of different data types (strings, structs, other cell arrays) and sizes. Because each of these objects may be non-scalar and can be of a different size/type, they cannot necessarily neighbor each other in memory.
When you pre-allocate a cell by doing
it is like you are creating N separate MATLAB variables except that they do not have distinct names (x,y,z, etc...) and they do not hold any data yet. If you place matrices in each cell location C{i}, then the matrix content of each C{i} individually will occupy contiguous memory, as usual. However, the data corresponding to different C{i} are like different variables and needn't neighbor each other.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!