## How does matlab handle removing elements memory wise?

### Bas Peters (view profile)

on 28 Jun 2019
Latest activity Edited by Stephen Cobeldick

on 28 Jun 2019

### Jan (view profile)

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.

R2019a

### Jan (view profile)

on 28 Jun 2019

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

#### 1 Comment

Stephen Cobeldick

on 28 Jun 2019
R2012b:
>> format debug
>> a = 1:5
a =
m = 1
n = 5
pr = ed13520
pi = 0
1 2 3 4 5
>> a(5) = []
a =
m = 1
n = 4
pr = 25bd8000
pi = 0
1 2 3 4
R2015b:
>> format debug
>> a = 1:5
a =
m = 1
n = 5
pr = cf0e09c0
pi = 0
1 2 3 4 5
>> a(5) = []
a =