Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Matlab warning me that "preallocation not recommended"

Tags:

matlab

I was writing up a function for the Coursera Machine Learning Course by Andrew Ng when I ran into a warning in Matlab. I haven't written what the answer should be but the starting code is all here except for one line for explanation purposes. The question is not fishing for the answer to the problem but an explanation of Matlab's warning.

The warning (not error) I get says:

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

Here's 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
like image 553
heretoinfinity Avatar asked Jun 21 '17 21:06

heretoinfinity


2 Answers

This was covered in a blog post by Loren Shure of The MathWorks, specifically under the section "A Common Misunderstanding". A small excerpt:

Users have been told so often to preallocate that we sometimes see code where variables are preallocated even when it is unnecessary. This not only complicates code, but can actually cause the very issues that preallocation is meant to alleviate, i.e., runtime performance and peak memory usage.

Drawing parallels between your situation and the example Loren gives, you preallocate g with the zeros function, but then reassign it with the result of 1./z. The memory allocated by the call to zeros is simply thrown away when 1./z is evaluated. This has the effect of requiring twice as much memory as needed, one chunk for the preallocated zeroes and one chunk for the result of 1./z.

In short, trust the Code Analyzer in this case.

like image 94
gnovice Avatar answered Nov 11 '22 07:11

gnovice


The line

g = zeros(size(z));

is redundant, because right after it you redefine g to be

g = 1./z;

like image 36
Miriam Farber Avatar answered Nov 11 '22 05:11

Miriam Farber