The is chosen such that is conjugate to . Initially, is using and equivalently the numerator of is rewritten as because and are orthogonal by design. The denominator is rewritten as using that the search directions pk are conjugated and again that the residuals are orthogonal. This gives the in the algorithm after cancelling . Example code in MATLAB / GNU Octave function x = conjgrad(A, b, x) r = b - A * x; p = r; rsold = r' * r; for i = 1:length(b) Ap = A * p; alpha = rsold / (p' * Ap); x = x + alpha * p; r = r - alpha * Ap; rsnew = r' * r; if sqrt(rsnew) < 1e-10 break end p = r + (rsnew / rsold) * p; rsold = rsnew; end end Numerical example Consider the linear system Ax = b given by we will perform two steps of the conjugate gradient method beginning with the initial guess in order to find an approximate solution to the system. Solution For reference, the exact solution is Our first step is to calculate the residual vector r0 associated with x0. This residual is computed from the formula r0 = b - Ax0, and in our case is equal to Since this is the first iteration, we will use the residual vector r0 as our initial search direction p0; the method of selecting pk will change in further iterations. We now compute the scalar using the relationship We can now compute x1 using the formula This result completes the first iteration, the result being an "improved" approximate solution to the system, x1. We may now move on and compute the next residual vector r1 using the formula Our next step in the process is to compute the scalar that will eventually be used to determine the next search direction p1. Now, using this scalar , we can compute the next search direction p1 using the relationship We now compute the scalar using our newly acquired p1 using the same method as that used for . Finally, we find x2 using the same method as that used to find x1. The result, x2, is a "better" approximation to the system's solution than x1 and x0. If exact arithmetic were to be used in this example instead of limited-precision, then the exact solution would theoretically have been reached after