function [] = tma4180s17_ex04_4() %% Test CG algorithm on linear systems with Hilbert matrices. n = [5 8 12 20]; tol = 1e-6; maxIter = 1e3; iterCount = zeros(length(n), 1); for i = 1:length(n) A = hilb(n(i)); b = ones(n(i), 1); x0 = zeros(n(i), 1); [~, iter] = cg(A, b, x0, tol, maxIter); iterCount(i) = iter; end % Plot results. bar(iterCount) set(gca,'XTickLabel', n, 'Color', 'none'); xlabel('Dimension', 'Interpreter', 'LaTeX', 'Fontsize', 14); ylabel('Iterations', 'Interpreter', 'LaTeX', 'Fontsize', 14); ylim([0, 1.05 * max(iterCount)]) end %% Algorithm 5.2 (CG) in N&W. % Stores A*p and dot(r, r) to reduce computation cost. function [x, iter] = cg(A, b, x, tol, maxIter) r = A * x - b; p = -r; rr = dot(r, r); for iter = 1:maxIter if norm(r) <= tol break end Ap = A * p; alpha = rr / dot(p, Ap); x = x + alpha * p; r = r + alpha * Ap; rrOld = rr; rr = dot(r, r); beta = rr / rrOld; p = -r + beta * p; end end