function xsol=myCG_PR(x0,tolf,maxIter)
% A matlab implementation of steepest descent with Exact Line search
% Use should supply: initial iterate x0
% tolx - tolerance between subsequent iterates xk and xk+1, norm(x_k+1 - x_k)
% tolf - tolerance for norm(F(x_k)) < tolf
% maxIter - the maximum number of iterations
fprintf('=============================================================================== \n')
fprintf('iteration        alphak         norm(grad) \n')
fprintf('=============================================================================== \n')

x0=x0(:);
alpha0=1;
k=0;
datasave=[];
xk=x0;
alphak=alpha0;
grad=-gradFun(x0);
gradOld=grad;
dk=-grad;
while ((norm(grad)>=tolf)) & (k<=maxIter)
    Q=hess(xk);
    dk=dk(:);
    gradOld=gradOld(:);
    alphak= -(dk'*gradOld)/(dk'*Q*dk);
    xk=xk+alphak*dk;
    grad=gradFun(xk);
    grad=grad(:);
    betak=grad'*(grad-gradOld)/(dk'*(grad-gradOld)); %Polak-Ribier
    dk=-grad + betak*dk;
    gradOld=grad;
    k=k+1;
    datasave=[datasave; k+1    alphak   norm(grad)];
end %end while
xsol=xk;
 disp(datasave)
 end

function F=myfun(x)
    F= 4*x(1)^2 + 2*x(2)^2 + 2*x(1)*x(2) + x(1)+x(2);
end
function grad=gradFun(x)
    grad(1) = 8*x(1)+2*x(2)+1;
    grad(2) = 2*x(1)+4*x(2)+1;
end

function Q=hess(x)
    Q(1,1)=8;
    Q(1,2)=2;
    Q(2,1)=2;
    Q(2,2)=4;
end

