matlabmemory-managementsharedparfor

MATLAB free memory without clear command


I need to free memory with Matlab without clear command (I'm inside a parfor loop of parallel toolbox and I can't call clear); I read that,for example, instead of

clear v  

I can set

v=[]

the question is: with '= []' I deallocate the memory of 'v' or just set v to an empty value and the previous memory is still allocated and then unusable? thanks


Solution

  • You read correctly. Here's a demonstration:

    My computer's memory right now (after clearing the workspace, but with some leftovers and plots in place):

    >> memory
    Maximum possible array:            54699 MB (5.736e+10 bytes) *
    Memory available for all arrays:            54699 MB (5.736e+10 bytes) *
    Memory used by MATLAB:             1003 MB (1.052e+09 bytes)
    Physical Memory (RAM):            32695 MB (3.428e+10 bytes)
    
    *  Limited by System Memory (physical + swap file) available.
    

    Allocate a billion element array and check memory again:

    >> x = rand(1e6,1e3);
    >> memory
    Maximum possible array:            46934 MB (4.921e+10 bytes) *
    Memory available for all arrays:            46934 MB (4.921e+10 bytes) *
    Memory used by MATLAB:             8690 MB (9.113e+09 bytes)
    Physical Memory (RAM):            32695 MB (3.428e+10 bytes)
    
    *  Limited by System Memory (physical + swap file) available.
    

    Set the variable to []. Most memory is again available (note a small loss):

    >> x = [];
    >> memory
    Maximum possible array:            54578 MB (5.723e+10 bytes) *
    Memory available for all arrays:            54578 MB (5.723e+10 bytes) *
    Memory used by MATLAB:             1061 MB (1.113e+09 bytes)
    Physical Memory (RAM):            32695 MB (3.428e+10 bytes)
    
    *  Limited by System Memory (physical + swap file) available.