Bird
0
0

What is the output of the following code?

medium📝 Predict Output Q4 of 15
NumPy - Broadcasting
What is the output of the following code?
import numpy as np
A = np.array([[1], [2], [3]])
B = np.array([10, 20, 30])
C = A + B
print(C)
A[[11 21 31] [12 22 32] [13 23 33]]
B[[11 12 13] [21 22 23] [31 32 33]]
C[[10 20 30] [10 20 30] [10 20 30]]
DError due to shape mismatch
Step-by-Step Solution
Solution:
  1. Step 1: Analyze shapes of A and B

    A shape is (3,1), B shape is (3,). B broadcasts to (1,3), A broadcasts to (3,3).
  2. Step 2: Perform broadcasting addition

    Each element of A's column is added to each element of B's row, resulting in a (3,3) array.
  3. Final Answer:

    [[11 12 13] [21 22 23] [31 32 33]] -> Option B
  4. Quick Check:

    Broadcast shapes (3,1) + (3,) = (3,3) [OK]
Quick Trick: Broadcast smaller dims to match larger dims for addition [OK]
Common Mistakes:
  • Assuming shapes must match exactly
  • Confusing which dimension broadcasts
  • Expecting error instead of broadcasting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes