How reshape and variable assignments are handled internally within MATLAB?
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
the cyclist
2015-10-9
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 个评论
the cyclist
2015-10-9
I don't know why. These are effectively identical times for me in R2015b on latest OS X.
更多回答(1 个)
Walter Roberson
2015-10-9
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Performance and Memory 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!