當我在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