2

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 points me to the last line in the loop warning me that allIamges grows inside the loop.

So what's the big deal here?

Shai
  • 111,146
  • 38
  • 238
  • 371
  • @EitanT missed that. I just flagged my answer asking it to be moved to that question. Thanks for spotting the duplicate. – Shai Jul 02 '13 at 12:18

1 Answers1

6

It is a big deal.

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

What happens behind the scenes?

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.


What can be done?

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. What if I don't know n beforehand?: There are several questions already dealing with this issue. For example this answer.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • 6
    +1, however, [R2011a has improved the situation](http://blogs.mathworks.com/steve/2011/05/20/more-about-automatic-array-growth-improvements-in-matlab-r2011a/) quite substantially. – Rody Oldenhuis Jul 02 '13 at 12:09
  • @RodyOldenhuis It would have driven me crazy... – Shai Jul 02 '13 at 12:12
  • 5
    woodchips has also written a nice post about this topic: http://stackoverflow.com/a/783137/97160 – Amro Jul 02 '13 at 12:58