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])
print(x + y)
AError due to incompatible shapes
B[[11 12 13] [21 22 23] [31 32 33]]
C[[10 20 30] [10 20 30] [10 20 30]]
D[[11 21 31] [12 22 32] [13 23 33]]
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of x and y

    x shape is (3,1), y shape is (3,). y broadcasts to (1,3).
  2. Step 2: Broadcasting rules apply

    x broadcasts across columns, y broadcasts across rows, resulting in shape (3,3). Addition is element-wise.
  3. Final Answer:

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

    Broadcasting expands x and y to (3,3) for addition [OK]
Quick Trick: Column vector plus row vector broadcasts to matrix [OK]
Common Mistakes:
  • Expecting shape error
  • Mixing row and column broadcasting
  • Assuming y repeats down rows instead of across columns

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes