MATLAB: At which cell sizes does it make sense to preallocate memory

MATLABmemorypreallocate memoryspeed

Hi everyone,
so the code analyzer throws me this message and tells me that i should consider preallocating memory for speed. So i'm wondering at about which size of a matrice does it make sense to do so? In my case it is a rather small one, eg. only about 80 rows and 6 collumns. Is the 'effort' even worth it? Are there some kind of guidelines? Thanks

Best Answer

From a speed perspective, it all depends on what is going on in your loop. If it takes you an hour to generate a row of the matrix, it doesn't matter if you waste 5 milliseconds to reallocate the matrix.
Theoretically, as soon as you have more than one iteration, you're wasting time since you are forcing matlab to a) create a bigger new matrix, b) copy the old matrix in the new one, c) delete the old matrix. You'll be doing that each iteration, so the more iterations, the more you'll be wasting. But for an arbitrary small number of iterations it won't be noticable. That number of iterations will depend on what goes on in the loop, as said, the speed of your processor and probably some other things.
Is the 'effort' even worth it?
It's puzzling that you see that as an effort. To me, not pre-allocating is more effort and more worries. What if the variable already exist before the loop but is bigger than needed? you'll end up with extra values in your matrix from the previous run. What if on the 10000th iteration you run out of memory adding an extra row? You'll have wasted 9999 iterations to get nothing whereas if you'd preallocated you'd have known before even starting that you didn't have enough memory.
I see no downside in preallocating, only benefits.