"Function with duplicate name cannot be defined" 错误但没有重复函数
"Function with duplicate name cannot be defined" error but no duplicate function
尝试在 Matlab 中编写梯度下降函数时出现以下错误:
Function with duplicate name "gradientDescent" cannot be defined
。我正在处理的程序有两个功能,当我删除第二个功能时,问题就消失了。鉴于这两个函数的名称完全不同,我不明白为什么会这样。这是代码:
function dJ = computeDerivative(X, y, theta, feature)
m = length(y); % number of training examples
hypothesis = X * theta;
error = ((hypothesis - y) / m) .* X(feature, :)
dJ = sum(error);
end
function theta = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
% theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by
% taking num_iters gradient steps with learning rate alpha
m = length(y); % number of training examples
for iter = 1:num_iters
for i = 1:length(theta)
theta(i) = theta(i) - alpha * computeDerivative(X, y, theta, i)
end
end
end
当您创建一个 MATLAB 函数时,每个函数都应该在一个单独的文件中,每个文件的名称应该与函数的名称相同。然而,如果你有一个主文件,并且你想要一些局部函数,你可以在同一个文件中编写局部函数,但只有主函数可以访问它。在您的情况下,computeDerivative 是主要函数,gradientDescent 是局部函数
尝试在 Matlab 中编写梯度下降函数时出现以下错误:
Function with duplicate name "gradientDescent" cannot be defined
。我正在处理的程序有两个功能,当我删除第二个功能时,问题就消失了。鉴于这两个函数的名称完全不同,我不明白为什么会这样。这是代码:
function dJ = computeDerivative(X, y, theta, feature)
m = length(y); % number of training examples
hypothesis = X * theta;
error = ((hypothesis - y) / m) .* X(feature, :)
dJ = sum(error);
end
function theta = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
% theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by
% taking num_iters gradient steps with learning rate alpha
m = length(y); % number of training examples
for iter = 1:num_iters
for i = 1:length(theta)
theta(i) = theta(i) - alpha * computeDerivative(X, y, theta, i)
end
end
end
当您创建一个 MATLAB 函数时,每个函数都应该在一个单独的文件中,每个文件的名称应该与函数的名称相同。然而,如果你有一个主文件,并且你想要一些局部函数,你可以在同一个文件中编写局部函数,但只有主函数可以访问它。在您的情况下,computeDerivative 是主要函数,gradientDescent 是局部函数