%% Solve Linear System with Several Right-Hand Sides
% Show how using decomposition objects can improve the efficiency of solving \textrm{Ax}=b with many right-hand sides.
%
% The inverse iteration is an iterative eigenvalue algorithm that solves linear systems with many right-hand sides. It is a method to iteratively compute an eigenvalue of a matrix starting from a guess of the corresponding eigenvector. Each iteration computes x = A\x, and then scales x by its norm.
% Create a sparse matrix A and random starting vectors x1 and x2.

n = 1e3;
rng default % for reproducibility
A = sprandn(n,n,0.2) + speye(n);
x1 = randn(n,1);
x2 = x1;

%
% Apply 100 iterations of the inverse iteration algorithm using backslash to calculate an eigenvalue of A.

tic
for ii=1:100
    x1 = A \ x1;
    x1 = x1 / norm(x1);
end
toc
lambda = x1'*A*x1

%
% Now use a decomposition object to solve the same problem.

tic
dA = decomposition(A); 
for ii=1:100
    x2 = dA \ x2;
    x2 = x2 / norm(x2);
end
toc
lambda = x2'*A*x2

% The performance of the algorithm improves dramatically because the matrix A does not need to be factorized during each iteration. Also, even though the backslash algorithm can be improved by performing an LU decomposition of A before the for-loop, the decomposition object gives access to all of the same performance gains without requiring that you write complex code.
%
%
% Copyright 2012 The MathWorks, Inc.