← back

Implement Orthogonal Projection of a Vector onto a Line

#66 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Compute the orthogonal projection of a vector onto a line defined by a direction vector. The projection gives the component of the vector that lies along the given direction.

Solution

1
2
3
4
5
6
7
8
9
10
import numpy as np

def orthogonal_projection(v, L):
    v = np.array(v, dtype=float)
    L = np.array(L, dtype=float)

    scalar = np.dot(v, L) / np.dot(L, L)
    projection = scalar * L

    return projection.tolist()

Explanation

  1. The projection of vector v onto direction L is given by: proj_L(v) = (v . L / L . L) * L.
  2. Compute the dot product of v and L for the numerator.
  3. Compute the dot product of L with itself for the denominator.
  4. Multiply the scalar ratio by L to get the projection vector.
  5. The result lies along the direction of L and is the closest point on the line to v.

Complexity

  • Time: O(n) where n is the dimensionality of the vectors
  • Space: O(n) for the output projection vector