Bird
0
0

Given a 2D array matrix of shape (5, 1) and a 1D array vec of shape (5,), you want to add them element-wise. Which code correctly uses broadcasting to do this?

hard📝 Application Q9 of 15
NumPy - Broadcasting
Given a 2D array matrix of shape (5, 1) and a 1D array vec of shape (5,), you want to add them element-wise. Which code correctly uses broadcasting to do this?
Aresult = matrix + vec
Bresult = matrix.T + vec
Cresult = matrix + vec.reshape(5, 1)
Dresult = matrix + vec.reshape(1, 1)
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of matrix and vec

    matrix shape is (5,1), vec shape is (5,). NumPy pads the vec shape on the left with 1s to make it (1,5).
  2. Step 2: Apply broadcasting

    matrix broadcasts across columns, vec across rows, resulting in shape (5,5) matrix with element-wise sums.
  3. Final Answer:

    result = matrix + vec -> Option A
  4. Quick Check:

    Direct broadcasting (5,1) + (5,) -> (5,5) matrix [OK]
Quick Trick: (n,1) + (n,) broadcasts directly to (n,n) matrix [OK]
Common Mistakes:
  • Reshaping vec to (5,1) for column-wise sum
  • Transposing matrix to row vector first
  • Reshaping vec to (1,1) causing reshape error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes