How does matlab handle removing elements memory wise?

8 次查看(过去 30 天)
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.

采纳的回答

Jan
Jan 2019-6-28
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 个评论
Stephen23
Stephen23 2019-6-28
编辑:Stephen23 2019-6-28
R2012b:
>> format debug
>> a = 1:5
a =
Structure address = fe793008
m = 1
n = 5
pr = ed13520
pi = 0
1 2 3 4 5
>> a(5) = []
a =
Structure address = fe793008
m = 1
n = 4
pr = 25bd8000
pi = 0
1 2 3 4
R2015b:
>> format debug
>> a = 1:5
a =
Structure address = 7849ccd0
m = 1
n = 5
pr = cf0e09c0
pi = 0
1 2 3 4 5
>> a(5) = []
a =
Structure address = 7849c790
m = 1
n = 4
pr = 98171e80
pi = 0
1 2 3 4

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Compiler 的更多信息

产品


版本

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by