+ % We use this in the inner loop.
+ sqrt_n = floor(sqrt(length(x0)));
+
+ % Set k=0 first, that way the references to xk,rk,zk,dk which
+ % immediately follow correspond (semantically) to x0,r0,z0,d0.
+ k = 0;
+
+ xk = x0;
+ rk = Q*xk - b;
+ zk = M \ rk;
+ dk = -zk;
+
+ while (k <= max_iterations && norm(rk, 'inf') > tolerance)
+ % Used twice, avoid recomputation.
+ rkzk = rk' * zk;
+
+ % The term alpha_k*dk appears twice, but so does Q*dk. We can't
+ % do them both, so we precompute the more expensive operation.
+ Qdk = Q * dk;
+
+ % We're going to divide by this quantity...
+ dkQdk = dk' * Qdk;
+
+ % So if it's too close to zero, we replace it with something
+ % comparable but non-zero.
+ if (abs(dkQdk) < eps)
+ dkQdk = sign(dkQdk)*eps;
+ end
+
+ alpha_k = rkzk/dkQdk;
+ x_next = xk + (alpha_k * dk);
+
+ % The recursive definition of r_next is prone to accumulate
+ % roundoff error. When sqrt(n) divides k, we recompute the
+ % residual to minimize this error. This modification was suggested
+ % by the second reference.
+ if (mod(k, sqrt_n) == 0)
+ r_next = Q*x_next - b;
+ else
+ r_next = rk + (alpha_k * Qdk);
+ end
+
+ z_next = M \ r_next;
+ beta_next = (r_next' * z_next)/rkzk;
+ d_next = -z_next + beta_next*dk;