When using cycles for populating arrays in MATLAB the code analyser throws warnings The variable 'foo' changes appears to change size on every loop iteration. Consider preallocating for speed.
Typical case:
for ii=1:3
foo(ii)=rand;
bar{ii}=rand;
end
this can be solved easily by preallocating, obviously.
foo=nan(3,1);bar=cell(3,1);
for ii=1:3
foo(ii)=rand;
bar{ii}=rand;
end
The problem is when I am not populating numeric or cell arrays but handle arrays, typically a set of lines to be accessible from different parts of code.
I have found one walkaround - loop backwards:
for ii=3:-1:1
foo(ii)=line(nan,nan);
end
But is there more neat way how to get rid of the warning, besides %#ok<*NASGU>
or %#ok<NASGU>
comments?
Since you are creating line objects, there is specifically a workaround for that which avoids a loop altogether. You can pass a matrix of values to line
to create one line per column. For example, this creates 3 line objects and stores the handles in a 3-by-1 vector:
h = line(nan(2, 3), nan(2, 3));