当我在Matlab中遇到警告时,我正在为Andrew Ng编写Coursera机器学习课程的函数。我没有写出答案应该是什么,但是出于解释目的,起始代码全部在这里,除了一行外。问题不在于解决问题的答案,而在于解释Matlab的警告。为什么Matlab警告我“不推荐使用预分配”
警告(不是错误)我得到说:
Line 6: The variable 'g' appears to be preallocated but preallocation is not recommended here
下面的代码
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
当您分配数组的各个元素时,预分配可能很有用。不是当您一次替换整个阵列时。 – aschepler