function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...
                                  num_features, lambda)
%COFICOSTFUNC Collaborative filtering cost function
%   [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...
%   num_features, lambda) returns the cost and gradient for the
%   collaborative filtering problem.
%

% Unfold the U and W matrices from params
X = reshape(params(1:num_movies*num_features), num_movies, num_features);
Theta = reshape(params(num_movies*num_features+1:end), ...
                num_users, num_features);

            
% You need to return the following values correctly
J = 0;
X_grad = zeros(size(X));
Theta_grad = zeros(size(Theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost function and gradient for collaborative
%               filtering. Concretely, you should first implement the cost
%               function (without regularization) and make sure it is
%               matches our costs. After that, you should implement the 
%               gradient and use the checkCostFunction routine to check
%               that the gradient is correct. Finally, you should implement
%               regularization.
%
% Notes: X - num_movies  x num_features matrix of movie features
%        Theta - num_users  x num_features matrix of user features
%        Y - num_movies x num_users matrix of user ratings of movies
%        R - num_movies x num_users matrix, where R(i, j) = 1 if the 
%            i-th movie was rated by the j-th user
%
% You should set the following variables correctly:
%
%        X_grad - num_movies x num_features matrix, containing the 
%                 partial derivatives w.r.t. to each element of X
%        Theta_grad - num_users x num_features matrix, containing the 
%                     partial derivatives w.r.t. to each element of Theta
%

t1 = (Theta*X')';
t2 = (t1-Y).^2;
t3 = t2(R==1); % only when movie has been rated.
temp = sum(t3(:));
J = (1/2) * (temp);

% adding regularization to cost
x_temp = X.^2;
theta_temp = Theta.^2;
reg_x = (lambda / 2) * sum(x_temp(:));
reg_theta = (lambda / 2) * sum(theta_temp(:));
J = J  + reg_x + reg_theta;

%calculating gradients
temp1 = ((Theta*X')' - Y);
temp1(find(R==0)) = 0; % only when movie has been rated.
X_grad =  temp1 * Theta;
Theta_grad = temp1' * X; 

% adding regularization to gradients
X_temp2 = X.*lambda;
Theta_temp2 = Theta.*lambda;
X_grad = X_grad + X_temp2;
Theta_grad = Theta_grad + Theta_temp2;
% =============================================================

grad = [X_grad(:); Theta_grad(:)];

end
