Broadcasting, precisely in Python
Shapes align from the right; a dimension of one stretches.
import numpy as np
rows = np.arange(3).reshape(3, 1)
cols = np.arange(4).reshape(1, 4)
print((rows + cols).shape)
print(rows + cols)
values = np.arange(3)
print((values[:, np.newaxis] * values).shape)
print(np.broadcast_shapes((3, 1), (1, 4), (3, 4)))
How it works
- Trailing dimensions must match or be 1.
newaxisinserts the 1 you need to make that true.broadcast_shapesanswers the question without allocating.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 11
- Characters to type
- 254
- Tokens
- 100
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 57 seconds.
Step 4 of 4 in Types & shapes, step 12 of 22 in NumPy.