Reputation: 2337
I have an array of size 5x4 in MATLAB.
A = [ 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20];
Since MATLAB stores arrays in column-wise fashion, A
will be in memory in the following order
A = 1, 5, 9, 13, 17, 2, 6, 10, 14, 18, 3, 7, 11, 15, 19, 4, 8, 12, 16, 20
My question is what happens when I delete the last two columns/rows of A
:
A(:,3:4) = [];
or
A(4:5,:) = [];
Will MATLAB create (copy) a new array in a different part of the memory and assigns the new address to A
again or A
will still be in the same memory location?
Upvotes: 2
Views: 55
Reputation: 23888
Will MATLAB create (copy) a new array in a different part of the memory and assigns the new address to A again?
I'd say the answer is: probably, and it certainly may, but whether it actually does is not necessarily specified by the language documentation (at least not that I've seen).
Generally, because Matlab is a pass-by-value, copy-on-write language, any modification to the data inside an array can cause it to be reallocated and copied, because any other existing references to that array need to retain the old value. "In-place" modifications are just an optimization used in certain cases where Matlab can determine that an array value is contained within a local scope/workspace. So if there are any other references to that array held in A
, then the memory will definitely be reallocated and copied.
But if your A
array value was limited to that single reference, Matlab could in theory keep the same allocated memory for the array's underlying values, and just shuffle them around within that same block of memory, leaving some of it unused at the end. I doubt that it would actually do so, because that would waste memory, with no definite point where it would be reclaimed in the future.
As a practical matter, I would assume that it always does get copied to a newly allocated block of memory.
You could test a particular version of Matlab to see whether it does so in your case by checking the pointer addresses returned by mxGetData
in the MEX API before and after the modification, or looking at memory allocation in the profiler.
Upvotes: 2