Broadcasting: Add a Row Vector

Easy
~10 min
code completion

Broadcasting

NumPy broadcasting lets you add arrays with different shapes without explicit loops. A common pattern: adding a 1D row vector to every row of a 2D matrix.

X = np.array([[1, 2],
              [3, 4],
              [5, 6]])  # shape (3, 2)
v = np.array([10, 20]) # shape (2,)

X + v  # Broadcasting: v is added to every row
# [[11, 22],
#  [13, 24],
#  [15, 26]]

NumPy automatically "stretches" v along the first axis to match X's shape.

Your task:

Implement add_row_vector(X, v) that adds 1D vector v to every row of 2D matrix X.

Example Tests

3x2 matrix + length-2 vector

Input: {"X":[[1,2],[3,4],[5,6]],"v":[10,20]}

Expected: [[11,22],[13,24],[15,26]]

1x3 matrix + length-3 vector

Input: {"X":[[0,0,0]],"v":[1,2,3]}

Expected: [[1,2,3]]

Negative vector

Input: {"X":[[5,5],[10,10]],"v":[-5,-5]}

Expected: [[0,0],[5,5]]

Sign in to solve this problem

You can read the full problem statement above. Create a free account to run code in the browser, submit solutions, and track your progress.