Matlab:数组在循环内增长-那又如何呢? [英] Matlab: Array growing inside a loop - so what?

查看:189
本文介绍了Matlab:数组在循环内增长-那又如何呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码(将图像读取到巨大的矩阵中)

I have this code (reading images into a huge matrix)

allImages = [];
for ii = 1 : n
    img = imread( fileNames{ii} );
    img = imresize( rgb2gray(img), [100 100] );
    allImages = cat(3, allImages, img ); % append image to huge matrix
end

Matlab将我指向循环的最后一行,警告我allIamges在循环内增长.

Matlab points me to the last line in the loop warning me that allIamges grows inside the loop.

那么这里有什么大不了的?

So what's the big deal here?

推荐答案

这很重要.

就正确性而言-代码可以完成预期的工作.这里的问题是性能.

In term of correctness - the code does what is expected. The issue here is performance.

当将新图像附加到allImages时,Matlab必须为调整后的allImages查找内存的连续区域(即全部成块).通常,这需要为调整后的allImages分配新的内存,复制旧数据并取消分配旧的allImages.
这些在幕后进行的重新分配+复制操作(可能是在每次迭代中!)可能会非常耗时.

When a new image is appended to allImages, Matlab has to find a contiguous region of memory (i.e. all in one chunk) for the resized allImages. This usually entails a new memory allocation for the resized allImages, copying of old data and de-allocation of the old allImages.
These re-allocation + copy operations that occur behind the scene (probably at each iteration!) can be very time consuming.

1.预分配:如果您知道图像的数量和allImages的最终大小,请提前保留以下空间:

1. Pre-allocate: If you know the number of images and the final size of allImages, reserve this space beforehand:

allImages = zeros( 100, 100, n ); % pre-allocate, fill with zeros.
for ii = 1 : n
    % ...
    allImages(:,:, ii ) = img; % write into pre-allocated array
end

2.如果我事先不认识n怎么办?:已经有几个问题在解决此问题.例如此答案.

这篇关于Matlab:数组在循环内增长-那又如何呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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