---
title: Gram-Schmidt and QR
heading: Straightening a basis
eyebrow: A7 · Lesson 28 · Gram-Schmidt and QR
xp: 50
---

::: hook
Orthonormal bases make everything easy: coordinates are dot products, projections are $QQ^T$, and nothing is lost to rounding. But the bases problems hand you, the columns of a measurement matrix or a set of signal templates, are rarely perpendicular. **Gram-Schmidt** fixes that: it takes any independent vectors and straightens them, one at a time, into an orthonormal basis for the same space. Written as a factorization, $A = QR$, it's how good software solves least-squares problems.
:::

::: play
- $\mathbf{a}_1$ is fixed; turn and stretch $\mathbf{a}_2$.
- Gram-Schmidt keeps the direction of $\mathbf{a}_1$ as $\mathbf{q}_1$. From $\mathbf{a}_2$ it removes the part along $\mathbf{q}_1$ (the dashed arrow), leaving a perpendicular piece that becomes $\mathbf{q}_2$ after scaling to length 1.
- The readouts are the entries of $R$. What happens to $r_{22}$ as $\mathbf{a}_2$ lines up with $\mathbf{a}_1$?
:::
:::

```sim plot
view: complex
range: 3.5
slider: th = 0..180 step 1 = 60 °
slider: L = 0.5..3 step 0.1 = 2
arrow: 2 + 0.5*j | label: a₁
arrow: L*(1∠th) | color: ch2 | label: a₂
arrow: L*cos(th° - atan(0.25))*(1∠(atan(0.25)*180/pi)) | dashed | label: part along q₁
arrow: L*(1∠th) - L*cos(th° - atan(0.25))*(1∠(atan(0.25)*180/pi)) | from: L*cos(th° - atan(0.25))*(1∠(atan(0.25)*180/pi)) | color: ch3 | label: perpendicular part
arrow: 1∠(atan(0.25)*180/pi) | color: ch4 | label: q₁
readout: r11 = sqrt(4.25) | digits: 4
readout: r12 = L*cos(th° - atan(0.25)) | digits: 4
readout: r22 = L*abs(sin(th° - atan(0.25))) | digits: 4
```

::: predict
## After Gram-Schmidt, $A = QR$. What shape is $R$?

- [x] Upper triangular
- [ ] Lower triangular
- [ ] Diagonal
- [ ] Orthogonal

::: reveal
Upper triangular. $\mathbf{q}_1$ is built from $\mathbf{a}_1$ alone, $\mathbf{q}_2$ from $\mathbf{a}_1$ and $\mathbf{a}_2$, and so on, so column $j$ of $A$ is a combination of $\mathbf{q}_1, \ldots, \mathbf{q}_j$ only. The entries below the diagonal of $R$ are zero.
:::
:::

::: nameit
## The process

Given independent $\mathbf{a}_1, \ldots, \mathbf{a}_n$:

1. $\mathbf{q}_1 = \mathbf{a}_1/|\mathbf{a}_1|$.
2. For each next $\mathbf{a}_j$, subtract its components along the $\mathbf{q}$'s found so far, then normalize:

$$\mathbf{v}_j = \mathbf{a}_j - \sum_{i<j}(\mathbf{q}_i\cdot\mathbf{a}_j)\,\mathbf{q}_i \qquad \mathbf{q}_j = \frac{\mathbf{v}_j}{|\mathbf{v}_j|}$$

The $\mathbf{q}$'s span the same space as the $\mathbf{a}$'s, step by step.

## As a factorization

Record the numbers: $r_{ij} = \mathbf{q}_i\cdot\mathbf{a}_j$ for $i < j$, and $r_{jj} = |\mathbf{v}_j|$. Then

$$A = QR$$

with $Q$ having orthonormal columns and $R$ upper triangular with positive diagonal.

## Least squares with QR

The normal equations $A^TA\hat{\mathbf{x}} = A^T\mathbf{b}$ become $R\hat{\mathbf{x}} = Q^T\mathbf{b}$, one back substitution. That's better than forming $A^TA$, which squares the matrix's sensitivity to rounding (lesson 52). `np.linalg.lstsq` and `np.linalg.qr` work this way.

## In practice

Done exactly as written, rounding errors make the computed $\mathbf{q}$'s drift away from perpendicular when the $\mathbf{a}$'s are nearly dependent. **Modified Gram-Schmidt**, which subtracts each projection from the running vector one at a time, is much steadier; libraries use Householder reflections, which are steadier still.
:::

::: example
## Apply Gram-Schmidt to $\mathbf{a}_1 = (3, 4)$, $\mathbf{a}_2 = (1, 0)$.

::: solution
1. **Normalize $\mathbf{a}_1$.** $\mathbf{q}_1 = (0.6, 0.8)$, with $r_{11} = 5$.
2. **Project $\mathbf{a}_2$ onto it.**
   $$\begin{aligned} r_{12} &= \mathbf{q}_1\cdot\mathbf{a}_2 \\ &= 0.6 \end{aligned}$$
3. **Subtract the projection.**
   $$\begin{aligned} \mathbf{v}_2 &= (1, 0) - 0.6(0.6, 0.8) \\ &= (0.64, -0.48) \end{aligned}$$
4. **Normalize.** Its length is $r_{22} = 0.8$, so $\mathbf{q}_2 = (0.8, -0.6)$, and
   $$R = \begin{bmatrix}5 & 0.6\\0 & 0.8\end{bmatrix}$$
5. **Check.**
   $$\begin{aligned} \mathbf{q}_1\cdot\mathbf{q}_2 &= 0.48 - 0.48 \\ &= 0 \end{aligned}$$

**Answer:** $\mathbf{q}_1 = (0.6, 0.8)$ and $\mathbf{q}_2 = (0.8, -0.6)$, with $R = \begin{bmatrix}5 & 0.6\\0 & 0.8\end{bmatrix}$.
:::
:::

::: example
## Apply Gram-Schmidt to $\mathbf{a}_1 = (1, 1, 0)$, $\mathbf{a}_2 = (1, 0, 1)$.

::: solution
1. **Normalize $\mathbf{a}_1$.**
   $$\mathbf{q}_1 = \frac{1}{\sqrt 2}(1, 1, 0)$$
2. **Project $\mathbf{a}_2$ onto it.**
   $$\mathbf{q}_1\cdot\mathbf{a}_2 = \frac{1}{\sqrt 2}$$
3. **Subtract the projection.**
   $$\begin{aligned} \mathbf{v}_2 &= (1, 0, 1) - \tfrac{1}{2}(1, 1, 0) \\ &= (0.5, -0.5, 1) \end{aligned}$$
4. **Normalize.** Its length is $\sqrt{1.5} = 1.225$, so
   $$\mathbf{q}_2 = (0.408, -0.408, 0.816)$$

**Answer:** $\mathbf{q}_1 = \frac{1}{\sqrt2}(1, 1, 0)$ and $\mathbf{q}_2 = (0.408, -0.408, 0.816)$.
:::
:::

::: example
## Run Gram-Schmidt on the columns of $\begin{bmatrix}1 & 1 & 1\\\varepsilon & 0 & 0\\0 & \varepsilon & 0\\0 & 0 & \varepsilon\end{bmatrix}$ with $\varepsilon = 10^{-8}$, in double precision.

::: solution
1. **In exact arithmetic.** The three $\mathbf{q}$'s are perpendicular.
2. **Classical Gram-Schmidt in floating point.** $1 + \varepsilon^2$ rounds to 1, and the classical process, which computes every projection coefficient from the original column, returns
   $$\mathbf{q}_2\cdot\mathbf{q}_3 = 0.5$$
   so the vectors are 60° apart instead of 90°.
3. **Modified Gram-Schmidt.** It subtracts each projection from the running remainder as soon as each $\mathbf{q}$ is found. On the same matrix it gives
   $$\mathbf{q}_2\cdot\mathbf{q}_3 \approx 10^{-16}$$
4. **Library QR.** It uses Householder reflections, which are better still.

**Answer:** the classical process leaves $\mathbf{q}_2$ and $\mathbf{q}_3$ 60° apart, with $\mathbf{q}_2\cdot\mathbf{q}_3 = 0.5$; the modified process brings that down to about $10^{-16}$.
:::
:::

::: check
given: a = 3 | 5 | 8; b = 4 | 12 | 6
answer: sqrt(a^2 + b^2)
tolerance: 0.5%

## Gram-Schmidt starts on $\mathbf{a}_1 = (\given{a}, \given{b})$. What is $r_{11}$?

::: right
Right. $r_{11} = |\mathbf{a}_1|$ = {answer}.
:::

::: misses
- [a + b] Use the length, $\sqrt{a^2 + b^2}$.
- [any] Not yet. The length of $\mathbf{a}_1$.
:::
:::

::: check
given: a = 3 | 6; b = 4 | 8; c = 1 | 2; d = 0 | 5
answer: (a*c + b*d)/sqrt(a^2 + b^2)
tolerance: 0.5%

## With $\mathbf{a}_1 = (\given{a}, \given{b})$ and $\mathbf{a}_2 = (\given{c}, \given{d})$, what is $r_{12} = \mathbf{q}_1\cdot\mathbf{a}_2$?

::: right
Right. $\frac{\mathbf{a}_1\cdot\mathbf{a}_2}{|\mathbf{a}_1|}$ = {answer}.
:::

::: misses
- [a*c + b*d] $\mathbf{q}_1$ is a unit vector: divide by $|\mathbf{a}_1|$.
- [any] Not yet. Normalize $\mathbf{a}_1$, then dot with $\mathbf{a}_2$.
:::
:::

::: check
given: a = 3 | 6; b = 4 | 8; c = 1 | 2; d = 0 | 5
answer: abs(a*d - b*c)/sqrt(a^2 + b^2)
tolerance: 0.5%

## With $\mathbf{a}_1 = (\given{a}, \given{b})$ and $\mathbf{a}_2 = (\given{c}, \given{d})$, what is $r_{22}$, the length of the part of $\mathbf{a}_2$ perpendicular to $\mathbf{a}_1$?

::: right
Right. It's the parallelogram's area divided by its base: $\frac{|ad - bc|}{|\mathbf{a}_1|}$ = {answer}.
:::

::: misses
- [sqrt(c^2 + d^2)] That's all of $\mathbf{a}_2$. Remove the part along $\mathbf{q}_1$ first.
- [any] Not yet. $|\mathbf{a}_2|^2 = r_{12}^2 + r_{22}^2$.
:::
:::

::: check
given: x1 = 3 | 5 | 8; x2 = 4 | 12 | 15
answer: sqrt(x1^2 + x2^2)
tolerance: 0.5%

## $Q$ is a 2 × 2 orthogonal matrix and $\mathbf{x} = (\given{x1}, \given{x2})$. How long is $Q\mathbf{x}$?

::: right
Right. Orthogonal matrices preserve length: $|Q\mathbf{x}| = |\mathbf{x}|$ = {answer}.
:::

::: misses
- [x1 + x2] Length is $\sqrt{x_1^2 + x_2^2}$.
- [any] Not yet. $|Q\mathbf{x}|^2 = \mathbf{x}^TQ^TQ\mathbf{x} = \mathbf{x}^T\mathbf{x}$.
:::
:::

::: check
kind: choice

## Why solve least squares with $R\hat{\mathbf{x}} = Q^T\mathbf{b}$ instead of the normal equations $A^TA\hat{\mathbf{x}} = A^T\mathbf{b}$?

- [x] Forming $A^TA$ makes the problem more sensitive to rounding; QR avoids it
- [ ] QR gives a different, better answer in exact arithmetic
- [ ] $A^TA$ is never invertible
- [ ] QR doesn't need $\mathbf{b}$

::: right
Right. In exact arithmetic they agree, but $A^TA$ squares the condition number, so in floating point QR keeps about twice as many good digits for hard problems.
:::

::: misses
- [2] They give the same answer exactly; the difference is rounding.
- [3] With independent columns, $A^TA$ is invertible.
- [any] Think about rounding errors.
:::
:::

::: check
kind: python

## Write `gram_schmidt(A)` returning `(Q, R)` for a NumPy array with independent columns, using modified Gram-Schmidt: for each column, subtract its projections onto the earlier `q`'s one at a time from the running vector, then normalize.

```python starter
import numpy as np

def gram_schmidt(A):
    m, n = A.shape
    Q = np.zeros((m, n))
    R = np.zeros((n, n))
    # for j in range(n): v = A[:, j]; subtract (q_i . v) q_i for i < j; normalize
    return Q, R

A = np.array([[3.0, 1], [4, 0]])
Q, R = gram_schmidt(A)
print(Q); print(R)
```

```python solution
import numpy as np

def gram_schmidt(A):
    m, n = A.shape
    Q = np.zeros((m, n))
    R = np.zeros((n, n))
    for j in range(n):
        v = A[:, j].astype(float).copy()
        for i in range(j):
            R[i, j] = Q[:, i] @ v
            v -= R[i, j] * Q[:, i]
        R[j, j] = np.linalg.norm(v)
        Q[:, j] = v / R[j, j]
    return Q, R

A = np.array([[3.0, 1], [4, 0]])
Q, R = gram_schmidt(A)
print(Q); print(R)
```

```python tests
import numpy as np
A = np.array([[3.0, 1], [4, 0]])
Q, R = gram_schmidt(A)
assert np.allclose(R, [[5, 0.6], [0, 0.8]]), "For (3, 4) and (1, 0), R should be [[5, 0.6], [0, 0.8]]."
B = np.array([[1.0, 1, 0], [1, 0, 1], [0, 1, 1], [1, 1, 1]])
Q, R = gram_schmidt(B)
assert np.allclose(Q.T @ Q, np.eye(3)), "The columns of Q should be orthonormal: Q.T @ Q = I."
assert np.allclose(Q @ R, B), "Q @ R should give back A."
assert np.allclose(np.triu(R), R) and np.all(np.diag(R) > 0), "R should be upper triangular with a positive diagonal."
```

::: right
Right. That's QR. The modified version, subtracting from the running vector, keeps $Q$ much closer to orthonormal in floating point.
:::
:::

::: check
kind: parts
given: a = 3 | 5; b = 4 | 12

## Gram-Schmidt starts with $\mathbf{a}_1 = (\given{a}, \given{b})$ and $\mathbf{a}_2 = (1, 0)$.

::: part
answer: sqrt(a^2 + b^2)
tolerance: 0.5%

### What is $|\mathbf{a}_1|$, the first diagonal entry of $R$?

::: misses
- [a + b] Use the Pythagorean length.
- [any] $\sqrt{a^2 + b^2}$.
:::
:::

::: part
answer: a/sqrt(a^2 + b^2)
tolerance: 0.5%

### What is $\mathbf{q}_1\cdot\mathbf{a}_2$, the top-right entry of $R$?

::: misses
- [b/sqrt(a^2 + b^2)] $\mathbf{a}_2 = (1, 0)$ picks the first entry of $\mathbf{q}_1$.
- [any] $\mathbf{q}_1 = \mathbf{a}_1/|\mathbf{a}_1|$.
:::
:::
:::

::: check
kind: derivation
vars: x = 0.5..3

## Gram-Schmidt on $\mathbf{a}_1 = (1, 1)$, $\mathbf{a}_2 = (x, 0)$.

::: step
answer: x/sqrt(2)

### What is $\mathbf{q}_1\cdot\mathbf{a}_2$?
:::

::: step
answer: x/2

### Subtract that much of $\mathbf{q}_1$ from $\mathbf{a}_2$. What is the first entry of what's left?
:::

::: right
Right. What's left is $\frac x2(1, -1)$, perpendicular to $\mathbf{q}_1$; normalizing gives $\mathbf{q}_2$.
:::
:::

::: explain
## Why does Gram-Schmidt produce vectors that span the same space as the originals?

::: model
Each step only subtracts multiples of the $\mathbf{q}$'s already found, which are themselves combinations of the earlier $\mathbf{a}$'s, and then rescales. So $\mathbf{q}_j$ is a combination of $\mathbf{a}_1, \ldots, \mathbf{a}_j$, and running the steps backward, $\mathbf{a}_j$ is a combination of $\mathbf{q}_1, \ldots, \mathbf{q}_j$ with coefficients from $R$. Since each set can be built from the other, they span the same space, and independence guarantees no $\mathbf{v}_j$ is ever zero.
:::
:::

::: practice

::: check
given: a = 5 | 8; b = 12 | 15
answer: a/sqrt(a^2 + b^2)
tolerance: 0.5%

## What is the first component of $\mathbf{q}_1$ for $\mathbf{a}_1 = (\given{a}, \given{b})$?

::: misses
- [a] Divide by the length.
- [any] $a/|\mathbf{a}_1|$.
:::
:::

::: check
given: r12 = 3 | 5; r22 = 4 | 12
answer: sqrt(r12^2 + r22^2)
tolerance: 0.5%

## In $A = QR$, column 2 has $r_{12}$ = {r12} and $r_{22}$ = {r22}. How long is $\mathbf{a}_2$?

::: misses
- [r12 + r22] Perpendicular parts add by Pythagoras.
- [any] $\sqrt{r_{12}^2 + r_{22}^2}$.
:::
:::

::: check
given: a = 2 | 4; d = 3 | 5
answer: a*d

## $A = QR$ is square with $R = \begin{bmatrix}\given{a} & 7\\0 & \given{d}\end{bmatrix}$. What is $|\det A|$?

::: misses
- [any] $|\det Q| = 1$, so $|\det A| = \det R$.
:::
:::
:::
