%% Solve Sparse Linear System
% Solve a sparse linear system and use the results to see how much of vector b lies in the column space of S.
%
% Create a random 500-by-20 sparse matrix with 10% density and a vector of ones. Use qr to factorize the matrix into the factors R and C = Q'*b.

S = sprand(500,20,0.1);
b = ones(500,1);
[C,R] = qr(S,b,0);

%
% Use the results to solve \textrm{Sx}=b with x = R\C.

x = R\C;

%
% Consider the identity{\left\|b\right\|}^2 ={\left\|\textrm{Sx}-b\right\|}^2 +{\left\|C\right\|}^2.
% Dividing through by the norm of b, you get a new identity that shows how much of b lies in the column space of S:
% \frac{{\left\|\textrm{Sx}-b\right\|}^2 }{{\left\|b\right\|}^2 }+\frac{{\left\|C\right\|}^2 }{{\left\|b\right\|}^2 }=1.
% The first term tells how much of b does not lie in the column space of S, while the second term tells how much of b does lie in the column space of S.

t1 = norm(S*x-b)^2/norm(b)^2
t2 = norm(C)^2/norm(b)^2

%
% Copyright 2019 The MathWorks, Inc.