ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

NumPy Tutorial• 7 min read

NumPy Broadcasting Rules & Dimensional Expansion

How NumPy operates on arrays of differing shapes without copying data

Broadcasting allows arithmetic operations between arrays of different shapes by conceptually stretching dimensions of size 1 to match larger dimensions without copying memory.

The Two Golden Rules of Broadcasting

Rule 1: Dimensions are compared element-wise from right to left (trailing dimensions first).

Rule 2: Two dimensions are compatible if they are equal, or if one of them is 1.

If one dimension is 1, it is conceptually stretched to match the other. If dimensions mismatch and neither is 1, NumPy raises a ValueError: operands could not be broadcast together.

Broadcasting a 1D Row Vector Across a 2D Matrix
import numpy as np

# Matrix: shape (3, 3)
matrix = np.array([
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90]
])

# Mean of each column: shape (3,)
col_means = np.array([40, 50, 60])

# Mean-center each column via broadcasting
# (3, 3) - (3,) -> (3,) is broadcast across all rows
centered = matrix - col_means
print("Column-centered matrix:
", centered)
The (3,) row vector is broadcast across all 3 rows of the (3, 3) matrix.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Under NumPy broadcasting rules, can an array of shape (4, 1) be added to an array of shape (4, 5)?