function [x,rvec] = myCG(A, b, x0, max_itr, tol) x = x0; rvec = zeros(1,max_itr+1); r = b - A * x0; rvec(1) = norm(r, 2); d = r; delta_old = dot(r, r); for i = 1:max_itr s = A * d; alpha = delta_old / dot(d, s); x = x + alpha * d; r = r - alpha * s; delta_new = dot(r, r); beta = delta_new / delta_old; d = r + beta * d; delta_old = delta_new; rvec(i + 1) = delta_new; if delta_new < tol rvec = rvec(1:i+1); break end end end