2

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?

2
  • 1
    You can use gobjects. empty methods are another option. Commented Jan 17, 2018 at 22:22
  • Can you, please, elaborate on the empty method? Commented Jan 30, 2018 at 0:02

3 Answers 3

2

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));
Sign up to request clarification or add additional context in comments.

Comments

1

The function gobjects is designed for just this purpose - it will return you a preallocated array of matlab.graphics.GraphicsPlaceholder objects with a size that you specify. You can then fill the array with graphics objects such as lines.

Note that you can usefully test elements of that array with isgraphics - elements that are actual graphics handles will return true, whereas elements that are GraphicsPlaceholder will return false.

If you're specifically looking to just turn off the warning, then %#ok comments are the right way to do it. You can turn off the warning globally in your Preferences, which will mean you can omit the %#ok comment, but that will mean that you miss the warning for all preallocations, not just for arrays of graphics handles.

Comments

0

One solution is to store the handles in a double array:

foo = zeros(3,1);
for ii=1:3
  foo(ii)=double(line(nan,nan));
end

You can convert them back to handles using the handle() method. But you don't need to do it explicitly most of the time. You can use the get and set functions with the numeric representation directly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.