How reshape and variable assignments are handled internally within MATLAB?
5 views (last 30 days)
Show older comments
Mohammad Abouali
on 8 Oct 2015
Commented: the cyclist
on 9 Oct 2015
Does anyone know what exactly happens when you are trying to reshape a variable? So, let's say I have a large array called largeArray (of course) and I am reshaping it as follow:
largeArray=reshape(largeArray,s1,s2,s3,...,sn);
So, I am resizing largeArray and assigning it to itself. Is MATLAB recreating a whole new variable, also called largeArray, therefore, the data is actually copied? or does the MATLAB just goes internally change the dimension, without recopying the entire data?
The following code takes a long time:
n=8*1024*1024*1024/8;
largeArray=zeros(n,1);
largeArray=reshape(largeArray,64,n/64); %this line takes a long time, even longer than the above command.
%Actually so long that I force quit MATLAB. Didn't wait for it.
however, this doesn't take a long time:
n=8*1024*1024*1024/8;
largeArray=zeros(n,1);
largeArray=reshape(largeArray,32,n/32); %this returns almost immediately.
also assigning seems to behave funny:
n=8*1024*1024*1024/8;
largeArray=zeros(n,1);
newLargeArray=largeArray; % this comes back almost immediately
newLargeArray(1)=42; % This again takes long but similar to that of the zeros(n,1), i.e. when creating the array;
0 Comments
Accepted Answer
the cyclist
on 9 Oct 2015
I think at least some of your questions are answered in this documentation page about memory allocation.
For example, in your last example,
newLargeArray=largeArray;
does not require another copy of that array, because MATLAB can just reference the first one (since they are identical). But as soon as you do
newLargeArray(1)=42;
the arrays are no longer identical, so MATLAB has to make an actual copy.
Regarding the two reshape commands ... They both return very fast for me, as expected. MATLAB does not need to makes copies. (Even though they are different "shapes", they are stored in the same way, but with different indexing.)
2 Comments
the cyclist
on 9 Oct 2015
I don't know why. These are effectively identical times for me in R2015b on latest OS X.
More Answers (1)
Walter Roberson
on 9 Oct 2015
MATLAB generates a new descriptor with the same information as the other descriptor except for the dimensions, with both of them pointing to the same block of memory. The memory itself is not touched. The operation of creating a descriptor is done all the time in MATLAB, for the results of every operation, so it should be very fast.
1 Comment
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!