Broadcasting

ADVANCED NUMPY OPERATIONS


Broadcasting

What is Broadcasting?

Broadcasting allows NumPy to perform element-wise operations on arrays of different shapes without the need for manual reshaping or looping. Instead of repeating values, NumPy automatically expands smaller arrays to match the dimensions of larger ones.

Example: Broadcasting a 1D and 2D Array

import numpy as np
# Creating two arrays of different shapes
a = np.array([1, 2, 3])
b = np.array([[1], [2], [3]])
# Broadcasting: NumPy automatically expands 'b' to match 'a'
result = a + b
print("Array a:\n", a)
print("Array b:\n", b)
print("Broadcasted Addition Result:\n", result)

How does this work?

  • a has a shape of (3,) → [1, 2, 3]
  • b has a shape of (3,1) → [[1], [2], [3]]
  • NumPy broadcasts b to (3,3) and adds element-wise with a.

More Examples of Broadcasting

Broadcasting a Scalar to a Matrix

matrix = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 10
result = matrix + scalar
print(result)
# The scalar gets "broadcasted" to each element

Real-World Use Case:

Broadcasting is widely used in machine learning for normalization, feature scaling, and batch operations.