%% Supplying Initial Guess
% Examine the effect of supplying lsqr with an initial guess of the solution.
%
% Create a random rectangular 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.

A = sprand(700,900,0.1);
b = sum(A,2);

%
% Use lsqr 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 75 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 = 75;
x1 = lsqr(A,b,[],maxit);
x0 = 0.99*ones(size(A,2),1);
x2 = lsqr(A,b,[],maxit,[],[],x0);

% With an initial guess close to the expected solution, lsqr is able to converge in fewer iterations.
%
%% Returning Intermediate Results
% You also can use the initial guess to get intermediate results by calling lsqr 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] = lsqr(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 2019 The MathWorks, Inc.