Broadcasting: Add a Row Vector

~10 mincode completion

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

Examples

3x2 matrix + length-2 vector

Input
add_row_vector([[1, 2], [3, 4], [5, 6]], [10, 20])
Output
[[11, 22], [13, 24], [15, 26]]

1x3 matrix + length-3 vector

Input
add_row_vector([[0, 0, 0]], [1, 2, 3])
Output
[[1, 2, 3]]

Negative vector

Input
add_row_vector([[5, 5], [10, 10]], [-5, -5])
Output
[[0, 0], [5, 5]]

Hints

Hint 1

Work directly with the arguments X, v and return the result rather than printing it.

Hint 2

Watch for this: used python loop over rows.

Requirements

  • X: 2D array of shape (m, n)

  • v: 1D array of shape (n,)

  • Return 2D array of shape (m, n).

  • Use a fully vectorised implementation without Python loops

Constraints

  • Vectorised implementation only, no Python loops

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~10 min

8 employers weight this skill

3 quant funds, 2 big tech firms, 1 frontier lab, 1 autonomy company, 1 enterprise vendor. Top match scores 81.

Python
import numpy as np

def add_row_vector(X: np.ndarray, v: np.ndarray) -> np.ndarray:
    """
    Add row vector v to every row of matrix X.

    Args:
        X: 2D array of shape (m, n)
        v: 1D array of shape (n,)

    Returns:
        2D array of shape (m, n).
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.