c?import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) b = np.array([10, 20]) c = a + b
The array a has shape (2, 3) and b has shape (2,). NumPy tries to broadcast b to match a. But (2,) cannot be broadcast to (2,3) because the second dimension sizes differ and one is not 1. This causes a ValueError.
c after the addition?import numpy as np a = np.array([[1], [2], [3]]) b = np.array([10, 20, 30]) c = a + b
Array a has shape (3,1) and b has shape (3,). NumPy broadcasts b to (1,3) and then broadcasts both to (3,3). The addition sums each element of a with each element of b along the second axis.
import numpy as np x = np.ones((4, 1, 3)) y = np.ones((3, 4)) z = x + y
NumPy compares shapes from the right: (4,1,3) and (3,4) align as (4,1,3) and ( ,3,4). The last dimensions 3 and 4 differ and neither is 1, so broadcasting fails with a ValueError.
a and b before addition?import numpy as np a = np.ones((2, 1, 4)) b = np.ones((1, 3, 1)) c = a + b print(c.shape)
Shapes (2,1,4) and (1,3,1) broadcast to (2,3,4). Dimensions 1 expand to match the other array's size.
a with shape (5, 1, 7) and b with shape (1, 3, 1), which NumPy broadcasting rule allows their addition?NumPy compares array shapes from right to left. For each dimension, sizes must be equal or one must be 1. This allows arrays of different shapes to be broadcast together.