0

While trying to write a function for gradient descent in Matlab I got the following error: Function with duplicate name "gradientDescent" cannot be defined. The program I'm working on has two functions in it, and when I remove the second one the problem goes away. I don't understand why this is happening given that the two functions have completely different names. Here's the code:

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
Paco Poler
  • 201
  • 1
  • 3
  • 12
  • When do you get the error? – aarbelle Apr 17 '16 at 18:15
  • Put them in separate files. – beaker Apr 17 '16 at 18:16
  • I get the error when trying to call the 'gradientDescent' function in a second file. There's no function with the same name in the second file, and I didn't put it here because the fact that the error goes away after removing the second function from the original file makes me think the issue is local. – Paco Poler Apr 17 '16 at 18:22
  • "There's no function with the second name in the second file." Well, the file has to have the same name as the function that's in it. :/ – beaker Apr 17 '16 at 18:24
  • I'd suggest reading [the documentation on functions](http://www.mathworks.com/help/matlab/matlab_prog/types-of-functions.html) – sco1 Apr 17 '16 at 19:27

1 Answers1

0

When you create a MATLAB function, each function should be in a separate file and the name of each file should be identical to the name of the function. If however you have a main file, and you want some local function, you can write the local function in the same file, but only the main function will have access to it. In your case computeDerivative is the main function and gradientDescent is the local function

aarbelle
  • 1,023
  • 8
  • 17