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

n = 400; 
on = ones(n,1); 
A = spdiags([-2*on 4*on -2*on],-1:1,n,n);
b = sum(A,2);

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

x = minres(A,b);

% By default minres uses 20 iterations and a tolerance of 1e-6, and the algorithm is unable to converge in those 20 iterations for this matrix. Since the residual is on the order of 1e-2, it is a good indicator that more iterations are needed. You also can reduce the tolerance to make it easier for the algorithm to converge.
%
% Solve the system again using a tolerance of 1e-4 and 250 iterations.

x = minres(A,b,1e-4,250);

%
% Copyright 2019 The MathWorks, Inc.
%