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.