MATLAB: How does matlab handle removing elements memory wise

elementMATLABmemoryremove

If a = [1:5] and I want to remove the last element I can do a(5) = [];
Does this first create a copy of a for the first two elements and then remove the original a or does this action cost no extra memory?
I'm asking because I'm processing very large vectors with limited memory so when I processed a part I want to remove it to free up space.

Best Answer

You can use format debug to display the pointer to the memory (I cannot test this currently but hope, that this valuable tool is still working)
format debug
a = 1:5 % By the way: not square brackets needed, they just waste time
a(5) = []
  • Either Matlab creates a new variable with the required number of elements, copies the needed data and removed the former array.
  • Or Matlab reorders the elements of the array at first and calls myRealloc to re-allocate the array in the memory afterwards. For shrinking an array it is likely (but not guaranteed), that the former pointer is conserved.
If only some elements at the end of a vector are concerned, a Mex function can handle this efficiently by resetting the dimensions with mxSetN or mxSetM. Then the original memory is kept, but not all elements are used anymore. See also https://www.mathworks.com/matlabcentral/answers/353503-how-to-shrink-a-pre-allocated-array-in-a-c-mex#answer_278903
Related Question