Skip to main content

What is broadcasting?

Broadcasting is the mechanism that lets numpy-ts perform element-wise operations on arrays with different shapes without explicitly copying data. When you add a scalar to a matrix, or multiply a row vector by a column vector, broadcasting determines how the shapes align. numpy-ts follows NumPy’s broadcasting rules exactly.

The three rules

Broadcasting compares shapes element-wise, starting from the trailing (rightmost) dimensions:
  1. If the arrays have different numbers of dimensions, the shape of the smaller array is padded with 1s on the left until both shapes have the same length.
  2. Arrays with size 1 along a particular dimension act as if they had the size of the array with the largest shape along that dimension. The element is repeated virtually (no memory copy).
  3. If sizes disagree and neither is 1, broadcasting fails with an error.

Scalar broadcasting

The simplest case: a scalar broadcasts to match any array shape.
Shape alignment:

Vector-to-matrix broadcasting

A 1-D array broadcasts along the rows of a 2-D matrix:
Shape alignment:
To broadcast along the columns instead, reshape the vector to a column:
Shape alignment:

Outer product pattern

When a column vector meets a row vector, broadcasting produces the outer product:
Shape alignment:
You can also compute the outer product directly with np.outer(a, b), which flattens both inputs first.

Advanced 3D broadcasting

Broadcasting extends to any number of dimensions. Here is a 3-D example:
Shape alignment (dimension-by-dimension):
Each dimension either matches, or one of them is 1 and stretches to the other.

broadcast_to and broadcast_arrays

broadcast_to(array, shape)

Expand an array to a new shape using broadcasting rules. Returns a read-only view (no data is copied):

broadcast_arrays(...arrays)

Broadcast multiple arrays against each other, returning a list of arrays with a common shape:

broadcast_shapes(...shapes)

Compute the broadcasted shape without creating any arrays:

Shape compatibility errors

When shapes are incompatible, numpy-ts throws an error. Two dimensions are incompatible when they differ and neither is 1:
Here are more examples of incompatible shapes:

Visual shape alignment

When comparing shapes, numpy-ts right-aligns them and pads the shorter one with 1s on the left:
Broadcasting only creates virtual copies. The element at the size-1 dimension is reused via stride tricks (stride of 0), so memory usage stays proportional to the original array, not the broadcast shape.

Next steps

Slicing & Indexing

Select sub-arrays, rows, columns, and use fancy indexing.

Data Types

Understand the 13 supported dtypes and type promotion rules.