typestar

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

  1. Trailing dimensions must match or be 1.
  2. newaxis inserts the 1 you need to make that true.
  3. broadcast_shapes answers the question without allocating.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Types & shapes, step 12 of 22 in NumPy.

← Previous Next →