当我在Matlab中遇到警告时,我正在为Andrew Ng编写Coursera机器学习课程的函数.我没有写出答案应该是什么,但起始代码全部在这里,除了一行用于解释目的.问题不是捕获问题的答案,而是解释Matlab的警告.
我得到的警告(不是错误)说:
Line 6: The variable 'g' appears to be preallocated but preallocation is not recommended here
Run Code Online (Sandbox Code Playgroud)
这是代码
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
Run Code Online (Sandbox Code Playgroud)
这篇由 The MathWorks 的Loren Shure在博客文章中介绍,特别是在"A Common Misunderstanding"一节中.一小段摘录:
已经经常告诉用户预先分配我们有时会看到变量被预分配的代码,即使它是不必要的.这不仅使代码复杂化,而且实际上可能导致预分配意味着缓解的问题,即运行时性能和峰值内存使用.
绘制你的情况和例子罗兰给相似之处,你预分配g
与zeros
功能,但随后的结果重新分配它1./z
.zeros
在1./z
评估时,调用分配的内存将被丢弃.这样做的效果是需要两倍的内存,一个块用于预分配的零,一个块用于结果1./z
.
简而言之,在这种情况下,请相信代码分析器.
归档时间: |
|
查看次数: |
431 次 |
最近记录: |