%% Iterative Solution to Linear System
% Solve a square linear system using pcg with default settings, and then adjust the tolerance and number of iterations used in the solution process.
%
% Create a random symmetric sparse matrix A. Also create a vector b of the row sums of A for the right-hand side of \textrm{Ax}=b so that the true solution x is a vector of ones.

rng default
A = sprand(400,400,.5);
A = A'*A;
b = sum(A,2);

%
% Solve \textrm{Ax}=b using pcg. The output display includes the value of the relative residual error \frac{\left\|b-\textrm{Ax}\right\|}{\left\|b\right\|}.

x = pcg(A,b);

% By default pcg uses 20 iterations and a tolerance of 1e-6, and the algorithm is unable to converge in those 20 iterations for this matrix. However, the residual is close to the tolerance, so the algorithm likely just needs more iterations to converge.
%
% Solve the system again using a tolerance of 1e-7 and 150 iterations.

x = pcg(A,b,1e-7,150);

%
% Copyright 2019 The MathWorks, Inc.
%
%