  function [x,rVals] = cg2(A,b,kMax)
% x is the kMax iterate of the method of conjugate gradients applied to
% the nxn symmetric positive definite system Ax = b.
% This implementation is identical to cg0 except that it uses the Lanczos 
% iteration to generate the q-vectors and exploits the fact that the
% matrix Tk = Qk'*A*Qk is tridiagonal.
% rVals is a row vector with rVals(k) = norm(A*xk - b), k=1:kMax.
r = b;
rho_c = r'*r;
x = zeros(length(b),1);
for k=1:kMax
    if k==1
        p = r;
    else
        tau = rho_c/rho_minus;
        p = r + tau*p;
    end
    w = A*p;
    mu = rho_c/(p'*w);
    x = x + mu*p;
    r = r-mu*w;
    rho_minus = rho_c;
    rho_c = r'*r; 
    rVals(k) = norm(A*x-b);
end
