4

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?

NKN
  • 6,482
  • 6
  • 36
  • 55
  • 1
    What is your Matlab version? – Rafael Monteiro Apr 17 '14 at 13:43
  • possible duplicate of [matlab - consider preallocating for speed](http://stackoverflow.com/questions/2151636/matlab-consider-preallocating-for-speed) – Shai Apr 17 '14 at 13:49
  • version : 2013a & 2013b – NKN Apr 17 '14 at 13:51
  • 2
    I don't think this is a duplicate - after all NKN tried pre-allocating the variable, only to get another warning that advised against the pre-allocation he had chosen. – Schorsch Apr 17 '14 at 13:51
  • 1
    **Note** that the answers below might be useful, but the cause of this second warning is that the preallocation is in the wrong location. Don't preallocate the output to a function, preallocate inside your function, just outside the loop. – Cris Luengo Feb 22 '19 at 15:52

3 Answers3

9

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.

SdaliM
  • 105
  • 4
CitizenInsane
  • 4,755
  • 1
  • 25
  • 56
4

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.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
3

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.

Community
  • 1
  • 1
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113