%% Supplying Initial Guess
% Examine the effect of supplying bicgstab with an initial guess of the solution.
%
% Create a tridiagonal sparse matrix. Use the sum of each row as the vector for the right-hand side of \textrm{Ax}=b so that the expected solution for x is a vector of ones.

n = 900;
e = ones(n,1);
A = spdiags([e 2*e e],-1:1,n,n);
b = sum(A,2);

%
% Use bicgstab to solve \textrm{Ax}=b twice: one time with the default initial guess, and one time with a good initial guess of the solution. Use 50 iterations and the default tolerance for both solutions. Specify the initial guess in the second solution as a vector with all elements equal to 0.99.

maxit = 50;
x1 = bicgstab(A,b,[],maxit);
x0 = 0.99*e;
x2 = bicgstab(A,b,[],maxit,[],[],x0);

% In this case supplying an initial guess enables bicgstab to converge more quickly.
%
%% Returning Intermediate Results
% You also can use the initial guess to get intermediate results by calling bicgstab in a for-loop. Each call to the solver performs a few iterations and stores the calculated solution. Then you use that solution as the initial vector for the next batch of iterations.
% For example, this code performs 100 iterations four times and stores the solution vector after each pass in the for-loop:

x0 = zeros(size(A,2),1);
tol = 1e-8;
maxit = 100;
for k = 1:4
    [x,flag,relres] = bicgstab(A,b,tol,maxit,[],[],x0);
    X(:,k) = x;
    R(k) = relres;
    x0 = x;
end

% X(:,k) is the solution vector computed at iteration k of the for-loop, and R(k) is the relative residual of that solution.
% Copyright 2020 The MathWorks, Inc.
%
%