title: Supplied objective function must return a scalar value
body: <p>I am trying to code a ML algorithm in Matlab. These are my different functions:</p>
  
  <p>sigmoid.m:</p>
  
  <pre><code>function g = sigmoid(z)
  g = zeros(size(z));
  g = 1 ./ (1+exp(z));
  </code></pre>
  
  <p>costFunction.m</p>
  
  <pre><code>function [J, grad ] = costFunction(theta, X, y)
  
  m = length(y); % number of training examples
  z = -X * theta;
  g = sigmoid(z);
  J = 1/m * ((-y * log(g)') - ((1 - y) * log(1 - g)'));
  
  grad = zeros(size(theta'));
  grad = (1/m) * (X' * (g - y));
  </code></pre>
  
  <p>ex2.m (This is the main file of my project and I put the relative lines I get this error message)</p>
  
  <pre><code>options = optimset('GradObj', 'on', 'MaxIter', 400);
  
  [theta, cost] = ...
      fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);
  </code></pre>
  
  <p>The error message:</p>
  
  <blockquote>
    <p>Error using fminunc (line 348) Supplied objective function must return
    a scalar value.</p>
    
    <p>Error in ex2 (line 97)    fminunc(@(t)(costFunction(t, X, y)),
    initial_theta, options);</p>
  </blockquote>
  
  <p>I don't know is there enough information above or not? If not, let me know to add extra information.</p>