Clearing a cell array does not release memory held by cell contents
3 views (last 30 days)
Show older comments
I have a script that creates some cell arrays and then populates the cells at various levels with arrays of different sizes. At the end of this script, memory is tight and so I try to clear a few of the larger cell arrays that are not needed. When I try to clear the cell on the command line like so:
clear acell
this seems like it releases the header information only for the cell array. When I type
memory
it does not show a significant amount of memory released. Even when I go through a loop and manually release each array in the cell structure like this:
acell{idx} = [];
before clearing the cell structure, the memory is not freed. The OS shows that matlab is using less memory, but I cannot allocate arrays without running out of memory. I am running Matlab R2012a on Windows XP, 32 bit.
I would appreciate any insight that you have. Thanks for your help!
Alan
2 Comments
James Tursa
on 23 May 2012
Can you post a short script that builds & clears the memory to show the apparent problem?
Accepted Answer
More Answers (1)
Walter Roberson
on 23 May 2012
Suppose you do
Z = zeros(1e5,1e5);
A{1} = Z;
A{2} = Z;
Then because of MATLAB's copy-on-write semantics, A{1} and A{2} would point to the same memory block as Z points to, and will continue to point to that block until they are altered. If you were to now clear A{1}, then very little memory would be saved, as most of the work would just be in reducing the "number of times in use" counter for that memory block. Not until the last user of the block releases it (the count reaches 0) is the memory actually freed.
5 Comments
James Tursa
on 24 May 2012
I am wondering if there is ever going to be some code for us to look at ...
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!