Why Matlab warns me that "preallocation is not recommended",

I wrote a feature for the Coursera Andrew Ng machine learning course when I met a warning in Matlab. I did not write that I should answer, but the source code is here, except for one line for explanation. The question is not to fish to answer the problem, but the explanation for Matlab's warning.

The warning (not the error) that I get says:

Line 6: The variable 'g' appears to be preallocated but preallocation is not recommended here 

Here is the code

 function g = sigmoid(z) %SIGMOID Compute sigmoid function % g = SIGMOID(z) computes the sigmoid of z. % You need to return the following variables correctly g = zeros(size(z)); % ====================== YOUR CODE HERE ====================== % Instructions: Compute the sigmoid of each value of z (z can be a matrix, % vector or scalar). g = 1./z; % ============================================================= end 
+5
source share
2 answers

This was described on the Loren Shure blog on MathWorks, in particular in the General Misunderstanding section. Short shutter speed:

Users were often told to indicate in advance that sometimes we see code where the variables are pre-allocated, even if this is not necessary. This not only complicates the code, but can actually cause those problems that pre-location is intended to facilitate, i.e. Runtime performance and peak memory usage.

Drawing parallels between your situation and the example that Loren gives, you first select g with the zeros function, and then reassign it with the result 1./z . The memory allocated by the zeros call is simply discarded when 1./z is 1./z . This leads to the fact that it takes twice as much memory as necessary, one block for pre-allocated zeros and one fragment for the result 1./z .

In short, trust Code Analyzer in this case.

+7
source

Line

g = zeros(size(z));

is redundant because immediately after it you redefine g as

g = 1./z;

+2
source

Source: https://habr.com/ru/post/1269084/


All Articles