title: Error in my gradient descent function: Unable to perform assignment because the left and right sides have a different number of elements
body: <p>I am getting an error for my gradient descent algorithm. It seems that the error doesn't really have to do with the functionality of the actual gradient descent, but rather with a part of the function which keeps track of the cost for each iteration of gradient descent.</p>
  
  <p>Here is the line of code that sparks the error:</p>
  
  <pre><code>theta = gradientDescent(X, y, theta, alpha, iterations);
  </code></pre>
  
  <p>The error then says: <strong>"Unable to perform assignment because the left and right sides have a different number of elements."</strong></p>
  
  <p>But then underneath it says: "error in gradientDescent line 30..." and then refers to this line in my gradient descent function:</p>
  
  <pre><code>J_history(iter) = computeCost(X, y, theta);
  </code></pre>
  
  <p>I am sooooo confused.</p>
  
  <p>Here is the full gradient descent function code:</p>
  
  <pre><code>function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
  %GRADIENTDESCENT Performs gradient descent to learn theta
  %   theta = GRADIENTDESCENT(X, y, theta, alpha, num_iters) updates theta by 
  %   taking num_iters gradient steps with learning rate alpha
  
  % Initialize some useful values
  m = length(y); % number of training examples
  J_history = zeros(num_iters, 1);
  
  for iter = 1:num_iters
  
      % ====================== YOUR CODE HERE ======================
      % Instructions: Perform a single gradient step on the parameter vector
      %               theta. 
      %
      % Hint: While debugging, it can be useful to print out the values
      %       of the cost function (computeCost) and gradient here.
      %
      h = X*theta;
      errors = h - y;
  
      theta = theta - alpha*(1/m)*sum(errors).*transpose(X);
  
  
  
  
  
  
      % ============================================================
      J_history(iter) = computeCost(X, y, theta);
      % Save the cost J in every iteration    
  
  
  end
  
  end
  </code></pre>
  
  <p>Any insight here would be soooo appreciated. </p>
  
  <p>Thanks,
  Mark</p>