← back

2D Translation Matrix Implementation

#55 · Linear Algebra · Medium

⊣ Solve on deep-ml.com

Problem

Implement a 2D translation matrix. Given translation amounts dx and dy, construct a 3x3 homogeneous transformation matrix that translates 2D points and apply it to a set of points.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import numpy as np

def translate_2d(points, dx, dy):
    points = np.array(points, dtype=np.float64)

    translation_matrix = np.array([
        [1, 0, dx],
        [0, 1, dy],
        [0, 0, 1]
    ], dtype=np.float64)

    n = points.shape[0]
    ones = np.ones((n, 1))
    homogeneous = np.hstack([points, ones])

    translated = (translation_matrix @ homogeneous.T).T

    return translated[:, :2].tolist()

Explanation

  1. Build the 3x3 homogeneous translation matrix with dx and dy in the last column.
  2. Convert 2D points to homogeneous coordinates by appending a column of ones.
  3. Multiply the translation matrix by the transposed point matrix, then transpose back.
  4. Extract the first two columns (x, y) from the result, discarding the homogeneous coordinate.

Complexity

  • Time: O(n) where n is the number of points
  • Space: O(n) for the transformed points