function [ x,r,i ] = conj_grad(A,x,b,tol)
% x and b must be column vectors

if nargin<4
    tol = 1e-9;
end

n = length(b);
r = b - A*x;
s = r;

for i = 1:n
    As = A*s;
    alpha = (s'*r)/(s'*As);
    x = x + alpha*s;
    r = b - A*x;
    if norm(r) <= tol
        return
    else
        beta = -(r'*As)/(s'*As);
        s = r + beta*s;
    end
end

end

