%% Permuted QR Decomposition
% Specify three output arguments to return a permutation matrix or vector that reduces fill-in in the R factor of the QR decomposition.
%
% Compute the QR decomposition of the west0479 sparse matrix. Specify three outputs to return a permutation matrix that satisfies \textrm{AP}=\textrm{QR}.

load west0479
A = west0479;
[Q,R,P] = qr(A);

%
% Verify that A*P = Q*R for the permutation matrix P, within machine precision.

norm(A*P-Q*R,'fro')

%
% Now specify the 'vector' option to return p as a permutation vector.

[Q,R,p] = qr(A,'vector');

%
% Verify that A(:,p) = Q*R for the permutation vector p, within machine precision.

norm(A(:,p) - Q*R,'fro')

%
% Verify that the use of a permutation matrix or permutation vector in the decomposition results in an R factor with fewer nonzeros for sparse inputs compared to a nonpermuted decomposition.

[Q1,R1] = qr(A);
spy(R1)
spy(R)

% The results show that the permuted decomposition produces an R factor with substantially fewer nonzeros.
% Copyright 2019 The MathWorks, Inc.