v9.1.1
Menu

Gram-Schmidt Orthonormalization

Implement the Gram-Schmidt process to orthonormalize a set of vectors using NumPy.

Given a list of linearly independent vectors, produce an orthonormal basis where:

  • Each output vector is unit length (norm = 1)
  • All output vectors are mutually orthogonal (dot product = 0)

The Gram-Schmidt process:

  1. Start with the first vector, normalize it: u1=v1∥v1∥\mathbf{u}_1 = \frac{\mathbf{v}_1}{\|\mathbf{v}_1\|}
  2. For each subsequent vector vk\mathbf{v}_k:
    • Subtract projections onto all previous orthonormal vectors
    • wk=vk−∑j=1k−1(vk⋅uj)uj\mathbf{w}_k = \mathbf{v}_k - \sum_{j=1}^{k-1} (\mathbf{v}_k \cdot \mathbf{u}_j) \mathbf{u}_j
    • Normalize: uk=wk∥wk∥\mathbf{u}_k = \frac{\mathbf{w}_k}{\|\mathbf{w}_k\|}

This algorithm is fundamental in CV for creating orthonormal bases in feature spaces.

Example

Input
vectors = [[1, 1, 0], [1, 0, 1], [0, 1, 1]]
Output
[[0.7071, 0.7071, 0.0], [0.4082, -0.4082, 0.8165], [-0.5774, 0.5774, 0.5774]]
Reasoning
  • Input: three linearly independent vectors in R3\mathbb{R}^3: v1=[1,1,0]\mathbf{v}_1=[1,1,0], v2=[1,0,1]\mathbf{v}_2=[1,0,1], v3=[0,1,1]\mathbf{v}_3=[0,1,1]. The output is three unit vectors spanning the same space, in the same order.
  • First direction: ∥v1∥=2\|\mathbf{v}_1\|=\sqrt{2}, so u1=12[1,1,0]≈[0.7071,0.7071,0]\mathbf{u}_1=\frac{1}{\sqrt2}[1,1,0]\approx[0.7071, 0.7071, 0].
  • Second: v2⋅u1=12\mathbf{v}_2\cdot\mathbf{u}_1=\frac{1}{\sqrt2}, so the part of v2\mathbf{v}_2 along u1\mathbf{u}_1 is 12[1,1,0]\frac12[1,1,0]. Removing it leaves w2=[0.5,−0.5,1]\mathbf{w}_2=[0.5,-0.5,1] with ∥w2∥=1.5≈1.2247\|\mathbf{w}_2\|=\sqrt{1.5}\approx1.2247, giving u2=16[1,−1,2]≈[0.4082,−0.4082,0.8165]\mathbf{u}_2=\frac{1}{\sqrt6}[1,-1,2]\approx[0.4082,-0.4082,0.8165].
  • Third: v3⋅u1=12\mathbf{v}_3\cdot\mathbf{u}_1=\frac{1}{\sqrt2} and v3⋅u2=16\mathbf{v}_3\cdot\mathbf{u}_2=\frac{1}{\sqrt6}. Subtracting 12[1,1,0]\frac12[1,1,0] and 16[1,−1,2]\frac16[1,-1,2] leaves w3=[−23,23,23]\mathbf{w}_3=[-\frac23,\frac23,\frac23], norm 23≈1.1547\frac{2}{\sqrt3}\approx1.1547, so u3≈[−0.5774,0.5774,0.5774]\mathbf{u}_3\approx[-0.5774,0.5774,0.5774].
  • Notice: every pair now has dot product 00 (e.g. 0.7071⋅0.4082−0.7071⋅0.4082+0=00.7071\cdot0.4082-0.7071\cdot0.4082+0=0), and the first output always points along v1\mathbf{v}_1, so reordering the inputs changes the basis. All components are rounded to 4 decimal places.

Constraints

  • Input: List of n vectors, each of dimension d
  • Vectors are linearly independent
  • Return: List of n orthonormal vectors (as lists)
  • Round each component to 4 decimal places

Learn this in

More from CV: Mathematical Foundations

solution.py

Test results

Sign in to run your code against the test cases.