MATLAB Answers

Pre-allocation of Cell Arrays

37 views (last 30 days)
MiauMiau
MiauMiau on 24 Mar 2014
Edited: Matt J on 24 Mar 2014
Hi
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?
And:
"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?
Thanks

  0 Comments

Sign in to comment.

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
C=cell(1,N)
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.

  0 Comments

Sign in to comment.

More Answers (0)