0

I am new to Matlab. Mlint tells that I need to preallocate the arrays to improve performance.Can anyone tell me how do I preallocate array size in following code snippet:

for jj= init_frame: nFrames

   im1 = double(mov(jj).cdata);
   color_hist_array(jj,:) = color_histogram(im1, bins);
   [spatio_gram_array(jj,:),mu(jj,:,:),sigma(jj,:,:,:)] = spatiogram(im1, bins);

Preallocation needs to be done in color_hist_array, spatio_gram_array, mu and sigma.

MaxSteel
  • 259
  • 1
  • 6
  • 18

3 Answers3

4

Preallocation is actually very easily done in matlab, in your case just by changing one line of code.

Use this and you should be done.

for jj=  nFrames:-1:init_frame

Because you do the loop backwards all variables start at maximum size and space is allocated at once.

Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122
3

Preallocation means that you first create a variable of the size you will need, and then fill in values. This is much faster than having the variable grow in size on every iteration of a loop, because growing requires allocating new memory of the new size, then copying the old data into the new memory.

Here's an example:

N = 10000;
x = zeros(1,N);
for i = 1:N
    x(i) = someFunction(i);
end

Dennis's answer about looping backward is a convenient trick to preallocate without extra lines of code before the loop.

Community
  • 1
  • 1
shoelzer
  • 10,648
  • 2
  • 28
  • 49
1

Read this and this link. In simple words, preallocation is just to tell MATLAB, how big your matrix is going to be (before you start using that Matrix). So that MATLAB can allocate sufficient memory. But there is much more analysis to this, which you will find in above links.

Autonomous
  • 8,935
  • 1
  • 38
  • 77