在Matlab preallocating阵列? [英] Preallocating arrays in Matlab?

查看:583
本文介绍了在Matlab preallocating阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是简单的循环裁剪大量图像,然后将它们存储在一个单元阵列。我不断收到消息:

I am using a simple for loop to crop a large amount of images and then storing them in a cell array. I keep getting the message:

变量 croppedSag 出现在每次循环迭代改变大小。考虑速度preallocating。

The variable croppedSag appears to change size on every loop iteration. Consider preallocating for speed.

我而在MATLAB编码之前见过几次。我一直忽略了它,并很好奇多少preallocating将如何增加运行时间,如果我有,比如说,10,000张或更大的数字?

I have seen this several times before while coding in MATLAB. I have always ignored it and am curious how much preallocating will increase the runtime if I have, say, 10,000 images or a larger number?

另外,我看了一下文档中的preallocating,它说,使用零()用于这一目的。我将如何使用,对于低于code?

Also, I have read about preallocating in the documentation and it says to use zeros() for that purpose. How would I use that for the code below?

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

我不太下面的示例中的文件中。

I didn't quite follow the examples in the documentation.

推荐答案

pre-分配的数组始终是在Matlab是一个好主意。另一种方法是有它通过循环每次迭代中生长的数组。每一个元素被添加到阵列的结束时间,Matlab的必须产生一个完全新的数组,旧数组的内容复制到新的一个,然后,最后,在结束添加新元素。 pre-清分无需分配一个新的阵列,并花时间阵列的现有内容复制到新的内存。

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.

不过,在你的情况,你可能不会看到那么多好处,你可能期望。当复制单元阵列到一个新的,放大单元阵列,MATLAB实际上并没有复制单元阵列的的内容的(图像数据),但只的指针数据。

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.

不过,没有理由不为pre-分配(除非你居然不知道事先的最终大小)。这是你的循环的pre-分配的版本:

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到二,所以它不会覆写虚数单位。

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

您也可以在一行中使用cellfun功能重新写这个循环:

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:

  • Matlab - Speed up your Code by Preallocating the size of Arrays, Cells, and Structures

这篇关于在Matlab preallocating阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆