v9.1.1
Menu

Array Broadcasting

mediumFREEBroadcastingNumPy BroadcastingNumPy Foundations

Problem Statement

Perform element-wise operations between arrays of different shapes.

Background

Broadcasting rules:

  1. Dimensions are compared from right to left
  2. Dimensions are compatible if equal or one of them is 1
  3. Arrays are "stretched" to match

Example: (3, 1) + (1, 4) → (3, 4)

Your Task

Write a function broadcast_arrays(row_vec, col_vec) that demonstrates broadcasting.

Given:

  • row_vec: Shape (1, n) - a row vector
  • col_vec: Shape (m, 1) - a column vector

Output Format

Return a dictionary with (all values as plain Python lists, not NumPy arrays):

  • "sum": row_vec + col_vec (broadcasts to m×n)
  • "product": row_vec * col_vec (broadcasts to m×n)
  • "result_shape": Shape of result (as list)

Example

Input
row = [[1, 2, 3]], col = [[10], [20]]
Output
{'sum': [[11, 12, 13], [21, 22, 23]], 'product': [[10, 20, 30], [20, 40, 60]], 'result_shape': [2, 3]}
Reasoning
  • Inputs: row_vec is a 1×31 \times 3 matrix holding 1,2,31, 2, 3 across its columns; col_vec is a 2×12 \times 1 matrix holding 10,2010, 20 down its rows.
  • Shape check: compare the shapes (1,3)(1, 3) and (2,1)(2, 1) from the right. Last axis: 33 vs 11, compatible, size 33. First axis: 11 vs 22, compatible, size 22. The result is 2×32 \times 3, which is why result_shape is [2, 3].
  • Stretching: the row is repeated down 2 rows and the column is repeated across 3 columns, so cell (row ii, column jj) pairs column value cic_i with row value rjr_j.
  • Sum: sij=ci+rjs_{ij} = c_i + r_j. Row 1 is 10+1,10+2,10+310+1, 10+2, 10+3 = [11, 12, 13]; row 2 is 20+1,20+2,20+320+1, 20+2, 20+3 = [21, 22, 23].
  • Product: pij=ci⋅rjp_{ij} = c_i \cdot r_j, giving [10, 20, 30] and [20, 40, 60], the outer product of the two vectors.
  • Notice the output has m⋅n=6m \cdot n = 6 entries: every column value meets every row value exactly once.

Constraints

  • row_vec has shape (1, n)
  • col_vec has shape (m, 1)

Learn this in

More from NumPy Foundations

solution.py

Test results

Sign in to run your code against the test cases.