My answer is a bit late, but there are a few things I'd mention regarding array growth and pre-allocation in MATLAB.
The first thing to note is that MATLAB has improved automatic array growth performance a lot in recent versions, so the performance hit implied by the warning might not be too bad if you do it right (see below). Still, best practice is to pre-allocate your array (e.g. with zeros
).
The Warning Explained
As of R2014a, the detailed explanation for the warning states the following:
The size of the indicated variable or array appears to be changing with each loop iteration. Commonly, this message appears because an array is growing by assignment or concatenation. Growing an array by assignment or concatenation can be expensive. For large arrays, MATLAB must allocate a new block of memory and copy the older array contents to the new array as it makes each assignment.
Programs that change the size of a variable in this way can spend most of their run time in this inefficient activity. ...
From this excerpt, it should be fairly clear why pre-allocation is a smart idea if you are at all concerned with performance.
Side note: There is limited information about the algorithm used for reallocation during array growth, but some information was provided on the same blog post by Steve Eddins, which I summarized in this previous answer.
Automatic Array Growth Optimization
If you want to use dynamic array resizing by growing along a dimension (without-preallocation), there are ways to do it right. See this this MathWorks blog post by Steve Eddins. The most important thing to note is that you should grow along the last dimension for best performance. This is not an issue in your case since the array is 1D. So, if you decide to let it ride, put %#ok<SAGROW>
on the same line as the warning, after the culprit code, to silence the warning.
Yair discusses dynamic array resizing in another post on his blog. Also, there are ways of allocating an array without initializing using some hairy MEX API acrobatics, but that's it.
Pre-allocation
Pre-allocation is recommended. Get in the habit, learn to love zeros
. If you are determined to squeeze every bit of performance out of MATLAB, Yair Altman has a couple of excellent articles on the topic of memory pre-allocation: