TExcelTAD
Home › Linear Algebra & Matrix Theory › The Gram-Schmidt Procedure

The Gram-Schmidt Procedure

The Gram-Schmidt procedure turns any linearly independent list of vectors into an orthonormal list with the same span. It is how orthonormal bases are built in practice, and in matrix form it is the QR factorization.

The idea

Take the vectors one at a time. Keep the first one. From each later vector, subtract its components along the directions already kept, so what remains is orthogonal to all of them. Normalize at the end (or as you go).

For independent v1,…,vk\mathbf{v}_1, \ldots, \mathbf{v}_k:

u1=v1u2=v2−⟨v2,u1⟩⟨u1,u1⟩u1u3=v3−⟨v3,u1⟩⟨u1,u1⟩u1−⟨v3,u2⟩⟨u2,u2⟩u2  ⋮uj=vj−∑i<j⟨vj,ui⟩⟨ui,ui⟩uiqj=uj∥uj∥\begin{aligned} \mathbf{u}_1 &= \mathbf{v}_1 \\ \mathbf{u}_2 &= \mathbf{v}_2 - \frac{\langle \mathbf{v}_2, \mathbf{u}_1 \rangle}{\langle \mathbf{u}_1, \mathbf{u}_1 \rangle} \mathbf{u}_1 \\ \mathbf{u}_3 &= \mathbf{v}_3 - \frac{\langle \mathbf{v}_3, \mathbf{u}_1 \rangle}{\langle \mathbf{u}_1, \mathbf{u}_1 \rangle} \mathbf{u}_1 - \frac{\langle \mathbf{v}_3, \mathbf{u}_2 \rangle}{\langle \mathbf{u}_2, \mathbf{u}_2 \rangle} \mathbf{u}_2 \\ &\ \ \vdots \\ \mathbf{u}_j &= \mathbf{v}_j - \sum_{i<j} \frac{\langle \mathbf{v}_j, \mathbf{u}_i \rangle}{\langle \mathbf{u}_i, \mathbf{u}_i \rangle} \mathbf{u}_i \\ \mathbf{q}_j &= \frac{\mathbf{u}_j}{\lVert \mathbf{u}_j \rVert} \end{aligned}

Each subtracted term is the projection of vj\mathbf{v}_j onto ui\mathbf{u}_i. Two facts make it work:

  • Orthogonality. By induction, u1,…,uj−1\mathbf{u}_1, \ldots, \mathbf{u}_{j-1} are mutually orthogonal, so ⟨uj,ui⟩=⟨vj,ui⟩−⟨vj,ui⟩⟨ui,ui⟩⟨ui,ui⟩=0\langle \mathbf{u}_j, \mathbf{u}_i \rangle = \langle \mathbf{v}_j, \mathbf{u}_i \rangle - \frac{\langle \mathbf{v}_j, \mathbf{u}_i \rangle}{\langle \mathbf{u}_i, \mathbf{u}_i \rangle}\langle \mathbf{u}_i, \mathbf{u}_i \rangle = 0 for each i<ji < j (all other terms vanish).
  • Same span, no zero vectors. uj\mathbf{u}_j is vj\mathbf{v}_j minus a combination of v1,…,vj−1\mathbf{v}_1, \ldots, \mathbf{v}_{j-1}, so span⁡(u1…uj)=span⁡(v1…vj)\operatorname{span}(\mathbf{u}_1 \ldots \mathbf{u}_j) = \operatorname{span}(\mathbf{v}_1 \ldots \mathbf{v}_j). If uj\mathbf{u}_j were 0\mathbf{0}, vj\mathbf{v}_j would lie in the span of the earlier vectors, contradicting independence.

Consequence. Every finite-dimensional inner product space has an orthonormal basis: start from any basis and run Gram-Schmidt.

By hand in exact arithmetic

python · try it yourself
from sympy import Matrix, Rational

def gram_schmidt(vs):
    us = []
    for v in vs:
        u = v
        for w in us:
            u = u - (v.dot(w) / w.dot(w)) * w
        us.append(u)
    return us

vs = [Matrix([1, 1, 0]), Matrix([1, 0, 1]), Matrix([0, 1, 1])]
us = gram_schmidt(vs)
for i, u in enumerate(us, 1):
    print(f"u{i} =", list(u), "  |u|^2 =", u.dot(u))
print("u1.u2, u1.u3, u2.u3 =", us[0].dot(us[1]), us[0].dot(us[2]), us[1].dot(us[2]))
u1 = [1, 1, 0]   |u|^2 = 2
u2 = [1/2, -1/2, 1]   |u|^2 = 3/2
u3 = [-2/3, 2/3, 2/3]   |u|^2 = 4/3
u1.u2, u1.u3, u2.u3 = 0 0 0

Dividing by the lengths gives q1=(1,1,0)/2\mathbf{q}_1 = (1, 1, 0)/\sqrt{2}, q2=(1,−1,2)/6\mathbf{q}_2 = (1, -1, 2)/\sqrt{6}, q3=(−1,1,1)/3\mathbf{q}_3 = (-1, 1, 1)/\sqrt{3}. SymPy has this built in as GramSchmidt(vs, orthonormal=True).

Tip: Scaling a uj\mathbf{u}_j by a convenient constant before continuing (2u2=(1,−1,2)2\mathbf{u}_2 = (1, -1, 2)) does not change the directions, and it keeps fractions out of hand calculations.

The matrix version: A=QRA = QR

Put v1,…,vk\mathbf{v}_1, \ldots, \mathbf{v}_k in the columns of AA and q1,…,qk\mathbf{q}_1, \ldots, \mathbf{q}_k in the columns of QQ. Each vj\mathbf{v}_j is a combination of q1…qj\mathbf{q}_1 \ldots \mathbf{q}_j only, with coefficients rij=⟨vj,qi⟩r_{ij} = \langle \mathbf{v}_j, \mathbf{q}_i \rangle, so

A=QR,Q has orthonormal columns (QTQ=I),R is upper triangular with rjj=∥uj∥>0A = QR, \qquad Q \text{ has orthonormal columns } (Q^TQ = I), \qquad R \text{ is upper triangular with } r_{jj} = \lVert \mathbf{u}_j \rVert > 0

NumPy's np.linalg.qr computes this (with Householder reflections, a more stable method; its signs may differ from Gram-Schmidt, so we fix them to make diag⁡(R)\operatorname{diag}(R) positive):

python · try it yourself
import numpy as np

A = np.array([[1.0, 1.0, 0.0],
              [1.0, 0.0, 1.0],
              [0.0, 1.0, 1.0]])
Q, R = np.linalg.qr(A)
s = np.sign(np.diag(R))          # make diag(R) positive, as Gram-Schmidt does
Q, R = Q * s, (R.T * s).T
print("Q =\n", np.round(Q, 4))
print("R =\n", np.round(R, 4))
print("Q^T Q = I:", np.allclose(Q.T @ Q, np.eye(3)), "  QR = A:", np.allclose(Q @ R, A))
Q =
 [[ 0.7071  0.4082 -0.5774]
 [ 0.7071 -0.4082  0.5774]
 [ 0.      0.8165  0.5774]]
R =
 [[1.4142 0.7071 0.7071]
 [0.     1.2247 0.4082]
 [0.     0.     1.1547]]
Q^T Q = I: True   QR = A: True

The columns of QQ are exactly q1,q2,q3\mathbf{q}_1, \mathbf{q}_2, \mathbf{q}_3 above (1/2≈0.70711/\sqrt{2} \approx 0.7071, 2/6≈0.81652/\sqrt{6} \approx 0.8165, 1/3≈0.57741/\sqrt{3} \approx 0.5774), and diag⁡(R)\operatorname{diag}(R) holds ∥u1∥=2\lVert \mathbf{u}_1 \rVert = \sqrt{2}, ∥u2∥=3/2\lVert \mathbf{u}_2 \rVert = \sqrt{3/2}, ∥u3∥=4/3\lVert \mathbf{u}_3 \rVert = \sqrt{4/3}.

Functions: Legendre polynomials

Gram-Schmidt works in any inner product space. Apply it to 1,x,x2,x31, x, x^2, x^3 with ⟨f,g⟩=∫−11fg dx\langle f, g \rangle = \int_{-1}^{1} f g \, dx:

python · try it yourself
from sympy import symbols, integrate, expand, Rational

x = symbols("x")
ip = lambda f, g: integrate(f * g, (x, -1, 1))

us = []
for v in [1, x, x**2, x**3]:
    u = v
    for w in us:
        u = u - ip(v, w) / ip(w, w) * w
    us.append(expand(u))
for u in us:
    print(u, "   scaled so p(1) = 1:", expand(u / u.subs(x, 1)))
1    scaled so p(1) = 1: 1
x    scaled so p(1) = 1: x
x**2 - 1/3    scaled so p(1) = 1: 3*x**2/2 - 1/2
x**3 - 3*x/5    scaled so p(1) = 1: 5*x**3/2 - 3*x/2

The scaled versions are the Legendre polynomials P0…P3P_0 \ldots P_3, used in Gaussian quadrature (the high-accuracy rule inside scipy.integrate) and in physics. SymPy prints x**2 for x2x^2; that is just its text format.

Numerical caution

Classical Gram-Schmidt in floating point can lose orthogonality badly when the input vectors are nearly dependent: tiny rounding errors in early ui\mathbf{u}_i get amplified. The modified version subtracts each projection from the running u\mathbf{u} (using u\mathbf{u} instead of v\mathbf{v} in the inner product), which is mathematically identical but much more stable. Library QR uses Householder reflections, see Numerical Linear Algebra.

In software

  • Least squares. Solving Rx=QTbR\mathbf{x} = Q^T\mathbf{b} is the stable way to fit models (Least Squares).
  • Eigenvalue algorithms. The QR algorithm behind np.linalg.eig repeats A→RQA \to RQ.
  • Graphics. Re-orthonormalizing a rotation matrix that drifted after many multiplications is a 3-vector Gram-Schmidt (see Look Rotation).
  • Krylov methods and LLM tooling. Arnoldi/Lanczos iterations for huge sparse matrices orthogonalize each new vector against the previous ones.

Exercises

Exercise 1: Two vectors in R2\mathbb{R}^2

Apply Gram-Schmidt to v1=(3,4)\mathbf{v}_1 = (3, 4), v2=(1,0)\mathbf{v}_2 = (1, 0) and normalize.

Answer

q1=(35,45)\mathbf{q}_1 = \left(\frac{3}{5}, \frac{4}{5}\right), q2=(45,−35)\mathbf{q}_2 = \left(\frac{4}{5}, -\frac{3}{5}\right).

Solution
u2=(1,0)−325(3,4)=(1−925,−1225)=(1625,−1225)∥u2∥=256+14425=2025=45q2=(1625,−1225)/45=(45,−35)\begin{aligned} \mathbf{u}_2 &= (1, 0) - \frac{3}{25}(3, 4) = \left(1 - \frac{9}{25}, -\frac{12}{25}\right) = \left(\frac{16}{25}, -\frac{12}{25}\right) \\ \lVert \mathbf{u}_2 \rVert &= \frac{\sqrt{256 + 144}}{25} = \frac{20}{25} = \frac{4}{5} \\ \mathbf{q}_2 &= \left(\frac{16}{25}, -\frac{12}{25}\right) \Big/ \frac{4}{5} = \left(\frac{4}{5}, -\frac{3}{5}\right) \end{aligned}

Exercise 2: Three vectors in R4\mathbb{R}^4

Orthogonalize v1=(1,1,1,1)\mathbf{v}_1 = (1, 1, 1, 1), v2=(1,1,0,0)\mathbf{v}_2 = (1, 1, 0, 0), v3=(1,0,1,0)\mathbf{v}_3 = (1, 0, 1, 0) (no need to normalize).

Answer

u1=(1,1,1,1)\mathbf{u}_1 = (1, 1, 1, 1), u2=(12,12,−12,−12)\mathbf{u}_2 = \left(\frac{1}{2}, \frac{1}{2}, -\frac{1}{2}, -\frac{1}{2}\right), u3=(12,−12,12,−12)\mathbf{u}_3 = \left(\frac{1}{2}, -\frac{1}{2}, \frac{1}{2}, -\frac{1}{2}\right).

Solution
u2=v2−24u1=(12,12,−12,−12)⟨v3,u1⟩⟨u1,u1⟩=24,⟨v3,u2⟩⟨u2,u2⟩=01=0u3=v3−12u1=(12,−12,12,−12)\begin{aligned} \mathbf{u}_2 &= \mathbf{v}_2 - \frac{2}{4}\mathbf{u}_1 = \left(\frac{1}{2}, \frac{1}{2}, -\frac{1}{2}, -\frac{1}{2}\right) \\ &\frac{\langle \mathbf{v}_3, \mathbf{u}_1 \rangle}{\langle \mathbf{u}_1, \mathbf{u}_1 \rangle} = \frac{2}{4}, \qquad \frac{\langle \mathbf{v}_3, \mathbf{u}_2 \rangle}{\langle \mathbf{u}_2, \mathbf{u}_2 \rangle} = \frac{0}{1} = 0 \\ \mathbf{u}_3 &= \mathbf{v}_3 - \frac{1}{2}\mathbf{u}_1 = \left(\frac{1}{2}, -\frac{1}{2}, \frac{1}{2}, -\frac{1}{2}\right) \end{aligned}
python · try it yourself
from sympy import Matrix, GramSchmidt
vs = [Matrix([1, 1, 1, 1]), Matrix([1, 1, 0, 0]), Matrix([1, 0, 1, 0])]
for u in GramSchmidt(vs):
    print(list(u))
[1, 1, 1, 1]
[1/2, 1/2, -1/2, -1/2]
[1/2, -1/2, 1/2, -1/2]

Exercise 3: What goes wrong?

What happens if you run Gram-Schmidt on (1,2)(1, 2), (2,4)(2, 4)?

Answer

u2=0\mathbf{u}_2 = \mathbf{0}, so normalization divides by zero: the vectors are dependent.

Solution

u2=(2,4)−105(1,2)=(0,0)\mathbf{u}_2 = (2, 4) - \frac{10}{5}(1, 2) = (0, 0). A zero uj\mathbf{u}_j is exactly the signal that vj\mathbf{v}_j is in the span of the earlier vectors. Practical code drops such vectors (with a tolerance) and continues, which gives an orthonormal basis of the span.

Exercise 4: Read R off the QR factorization (code)

For AA with columns (1,1,0)(1, 1, 0) and (2,0,1)(2, 0, 1), find QQ and RR with positive diagonal and check that r12=⟨v2,q1⟩r_{12} = \langle \mathbf{v}_2, \mathbf{q}_1 \rangle.

Answer

R=[2203]≈[1.41421.414201.7321]R = \begin{bmatrix} \sqrt{2} & \sqrt{2} \\ 0 & \sqrt{3} \end{bmatrix} \approx \begin{bmatrix} 1.4142 & 1.4142 \\ 0 & 1.7321 \end{bmatrix}, and ⟨v2,q1⟩=22=2\langle \mathbf{v}_2, \mathbf{q}_1 \rangle = \frac{2}{\sqrt{2}} = \sqrt{2}.

Solution

q1=(1,1,0)/2\mathbf{q}_1 = (1, 1, 0)/\sqrt{2}. ⟨v2,q1⟩=22=2\langle \mathbf{v}_2, \mathbf{q}_1 \rangle = \frac{2}{\sqrt{2}} = \sqrt{2}. u2=(2,0,1)−2⋅q1=(2,0,1)−(1,1,0)=(1,−1,1)\mathbf{u}_2 = (2, 0, 1) - \sqrt{2} \cdot \mathbf{q}_1 = (2, 0, 1) - (1, 1, 0) = (1, -1, 1), ∥u2∥=3\lVert \mathbf{u}_2 \rVert = \sqrt{3}.

python · try it yourself
import numpy as np
A = np.array([[1.0, 2.0], [1.0, 0.0], [0.0, 1.0]])
Q, R = np.linalg.qr(A)
s = np.sign(np.diag(R)); Q, R = Q * s, (R.T * s).T
print(np.round(R, 4))
print(round(float(A[:, 1] @ Q[:, 0]), 4))
[[1.4142 1.4142]
 [0.     1.7321]]
1.4142

Test yourself

In Gram-Schmidt, what is subtracted from vj\mathbf{v}_j?

  1. Its projections onto the previously built ui\mathbf{u}_i
  2. The average of the earlier vectors
  3. Its length
  4. Its projections onto the standard basis

In A=QRA = QR from Gram-Schmidt, RR is…

  1. diagonal
  2. orthogonal
  3. lower triangular
  4. upper triangular with positive diagonal

Gram-Schmidt on 1,x,x21, x, x^2 with ⟨f,g⟩=∫−11fg dx\langle f, g \rangle = \int_{-1}^{1} fg \, dx produces…

  1. Chebyshev polynomials
  2. Taylor polynomials
  3. Legendre polynomials (up to scaling)
  4. sines and cosines