# QR Factorization for Inconsistent Linear System

I am trying to recreate the problem found here on finding the least squares solution to an inconsistent linear system via QR factorization. Can someone explain the part about adding on vectors so that Q will span $R^5$? When I try to go through this in Matlab using the qr built-in function, my new R matrix is a 5x5 instead of a 5x3. Below is the code that I have thus far. From what I can tell, the only error is that my new R matrix is coming out as the wrong dimension.

A = [3 -1 2; 4 1 0; -3 2 1; 1 1 5; -2 0 3];
b = [10; 10; -5; 15; 0];
[Q,R]=qr(A,0)
% Add on additional vector to Q in order to span R^4
Qt = [Q(1,1) Q(1,2) Q(1,3) 1 0; Q(2,1) Q(2,2) Q(2,3) 0 1; Q(3,1) Q(3,2) Q(3,3) 0 0; Q(4,1) Q(4,2) Q(4,3) 0 0; Q(5,1) Q(5,2) Q(5,3) 0 0];
[Qnew,Rnew]=qr(Qt,0);
% Multiply Qnew with given b:
Qnewtran = transpose(Qnew);
bnew = Qnewtran*b;
x = Rnew\bnew

• So, you're saying that this is happening because my A matrix isn't full rank? – kathystehl Dec 12 '15 at 3:33

The Matlab function qr when applied to matrix $A$ (i.e. [Q,R]=qr(A)) makes the QR decomposition $$A=QR$$ with $Q$ a $5\times 5$ orthogonal matrix, $R$ a $5\times 3$ upper triangular and returns $Q,R$. Note that $Q,R$ can be decomposed as $$Q=[\matrix{Q_1 & Q_2}]\\R=\left[\matrix{R_1\\0}\right]$$ where $Q_1$ is a matrix consisting of the the first 3 columns of $Q$, $Q_2$ is a matrix consisting of the rest 2 columns of $Q$ and $R_1$ a $3\times 3$ upper triangular matrix which is invertible if $rank(A)=3$. Thus, the decomposition can be simplified as $$A=QR=[\matrix{Q_1 & Q_2}]\left[\matrix{R_1\\0}\right]=Q_1R_1$$ Since $Q$ is orthogonal it holds true that $Q_1^TQ_1=\mathbb{I}_3$. Now it is straightforward to prove that the solution of the equation is given by $$x=R_1^{-1}Q_1^Tb$$

So your MATLAB code should be something like that

[Q,R]=qr(A);

Q1=Q(:,1:3);

R1=R(1:3,:);

x=inv(R1)*Q1'*b;

• Or, you can use [Q1,R1]=qr(A,0) – Brian Borchers Jul 4 '16 at 16:46