Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
NumPy - Broadcasting
What will be the output of this code?
import numpy as np
X = np.array([[1], [2], [3]])
Y = np.array([10, 20, 30])
Z = X + Y
print(Z)
AError due to incompatible shapes
B[[11 21 31] [12 22 32]]
C[[11 21 31] [12 22 32] [13 23 33]]
D[[10 20 30] [10 20 30] [10 20 30]]
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes for broadcasting

    X shape is (3,1), Y shape is (3,). Y broadcasts to (1,3), X broadcasts to (3,1), result shape (3,3).
  2. Step 2: Calculate element-wise addition

    Each element of X added to each element of Y: first row [1+10,1+20,1+30], second row [2+10,2+20,2+30], third row [3+10,3+20,3+30].
  3. Final Answer:

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

    Broadcasting expands arrays to (3,3) for addition [OK]
Quick Trick: Broadcast column vector with row vector to get matrix [OK]
Common Mistakes:
  • Expecting error due to shape
  • Confusing shapes of X and Y
  • Misreading output dimensions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes