function [x,flag,relres,iter]=mycg(A,b,tol,maxit)
%Textbook page 128
n=length(b);
x=zeros(n,1);
r=b-A*x; r0=norm(r);
d=r; flag=1;relres=[];
for iter=1:maxit
relres=[relres;norm(r)/r0]; %store relative residuals
if(norm(r)/r0)<=tol
flag=0;break;
end
Ad=A*d;
alf=r'*r/(d'*Ad);
x=x+alf*d;
r_old=r;
r=r_old-alf*Ad;
beta=r'*r/(r_old'*r_old);
d=r+beta*d;
end