%% Solve Linear System with Economy-Size QR Factors
% Use the economy-size QR decomposition of a coefficient matrix to solve the linear system \textrm{Ax}=b.
%
% Create a 10-by-5 coefficient matrix by using the first five columns of magic(10). For the right-hand side of the linear equation \textrm{Ax}=b, use the row sums of the matrix. With this setup, the solution to the equation x should be a vector of ones.

A = magic(10);
A = A(:,1:5)
b = sum(A,2)

%
% Compute the economy-size QR decomposition of A. Then solve the linear system \textrm{QRx}=b with x(p,:) = R\(Q\b). Because Q is orthogonal, this equation is the same as x(p,:) = R\(Q'*b).

[Q,R,p] = qr(A,0)
x(p,:) = R\(Q\b)

%
% Make a semilog plot of the diagonal of R to confirm that the permuted decomposition produces an R factor with abs(diag(R)) decreasing. Plot the singular values of A in the same plot for comparison. In practice, the diagonal values of R behave in a similar way to the singular values of A. Therefore, you can use the diagonal values of R as a measure for how close to singular the matrix A is.

semilogy(abs(diag(R)),'-o')
hold on
semilogy(svd(A),'r-o')
legend('Diagonal of R','Singular Values of A')

%
% Copyright 2019 The MathWorks, Inc.
%