%% Solve Rectangular Sparse Linear System
% Use qr to solve the matrix equation \textrm{Sx}=B with a rectangular sparse coefficient matrix S.
%
% Load the west0479 sparse matrix and use the first 200 columns as the rectangular coefficient matrix in a linear system. For the right-hand side of the equation, use the row sums of S. With this setup, the solution to \textrm{Sx}=B is a vector of ones.

load west0479
S = west0479(:,1:200);
B = sum(S,2);

%
% Solve \textrm{Sx}=B using qr with two inputs and three outputs. The solution to the linear system is x = P*(R\C).

[C,R,P] = qr(S,B);
x = P*(R\C);

% Verify that \textrm{Sx}-B=0, within machine precision.

norm(S*x-B)

%
% Note: To calculate the upper-triangular factor R and permutation matrix P, but avoid computing the orthogonal matrix Q (which is often the most computationally expensive part of a call to qr), you can specify B as an empty matrix:

emptyB = zeros(size(S,1),0);
[~,R,P] = qr(S,emptyB);

%
% Copyright 2019 The MathWorks, Inc.