Question

When plotting a set of figures using a for loop, for example:

for ei=1:length(E),
  hnds(ei) = plot(1:nP, avgR(ei,:), [clrStr(ei),'-'] ); 
end 

There is a (the famous) warning in the code for the hnds(ei) variable:

The variable hnds(ei) appears to change size on every loop iteration. Consider pre-allocating for speed.

But when I try to pre-allocate the variable:

hnds = zeros(1,length(E));

there is another warning for this new line and in the details for pre-allocation it says:

Suggested Action: Avoid preallocating memory to a variable assigned to the output of another function.

Is there any way to remove this warning, or should just ignore it?

Was it helpful?

Solution 2

You can try iterate in reverse order to avoid the warning:

for ei=length(E):-1:1,
    hnds(ei) = plot(1:nP, avgR(ei,:), [clrStr(ei),'-'] ); 
end 

In this case you do not need to pre-allocate (i.e., no hnds = zeros(1,length(E));).

By iterating in reverse order, the array size hnds is determined in the first iteration and stays fixed throughout the iterations.

See this thread for more information.

OTHER TIPS

Just put special %#ok comment at the end of the line and it will disable all warnings associated with this line:

hnds = zeros(1,length(E)); %#ok

You can also use special %#ok<specific1, ...> comment to disable only very specific warnings but not other ones. Check this link for furhter details.

You can deactivate it in Preferences:

enter image description here

(Matlab 2013b)

I think it is not possible to suppress this certain warning in this certain loop of a single script, just global. It's different for warnings which are displayed in the command window, they can be suppressed individually.

Edit: I was wrong.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top