Preallocating arrays in Matlab?

╄→尐↘猪︶ㄣ 提交于 2019-11-27 16:07:52

Pre-allocating an array is always a good idea in Matlab. The alternative is to have an array which grows during each iteration through a loop. Each time an element is added to the end of the array, Matlab must produce a totally new array, copy the contents of the old array into the new one, and then, finally, add the new element at the end. Pre-allocating eliminates the need to allocate a new array and spend time copying the existing contents of the array into the new memory.

However, in your case, you might not see as much benefit as you might expect. When copying the cell array to a new, enlarged cell array, Matlab doesn't actually have to copy the contents of the cell array (the image data), but only pointers to that data.

Nonetheless, there is no reason not to pre-allocate (unless you actually don't know the final size in advance). Here's a pre-allocated version of your loop:

croppedSag = cell(1, sagNum);
for ii = 1:sagNum
    croppedSag{ii} = imcrop(SagArray{ii}, rect);
end

I also changed the index variable "i" to "ii" so that it doesn't over-write the imaginary unit.

You can also re-write this loop in one line using the cellfun function:

croppedSag = cellfun(@(im) imcrop(im, rect), SagArray);

Here's a blog entry that might be informative:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!