Broadcasting rules allow NumPy to perform operations on arrays of different shapes. Here’s a simple explanation:
-
Same Shape: If two arrays have the same shape, they can be operated on element-wise.
-
Different Shapes: If the shapes are different, NumPy tries to "broadcast" the smaller array across the larger one. This means:
- Starting from the trailing dimensions, NumPy compares the shapes.
- If the dimensions are equal or one of them is 1, broadcasting can occur.
- If the dimensions are not compatible (i.e., neither is 1), an error is raised.
-
Example:
- Array A: shape (3, 4)
- Array B: shape (4)
- Array B is broadcasted to shape (3, 4) to match Array A.
This allows for efficient computation without needing to manually expand the smaller array.
