Bird
0
0

How can you broadcast these arrays to add them correctly?

hard📝 Application Q8 of 15
NumPy - Broadcasting
You have a 3D array of shape (2, 3, 1) representing 2 samples, 3 features, and 1 measurement each. You want to add a 2D array of shape (3, 4) representing 4 measurements for each feature. How can you broadcast these arrays to add them correctly?
AAdd directly without reshaping, broadcasting works automatically
BTranspose the 3D array to (3, 2, 1) and add directly
CReshape the 3D array to (2, 3) and add to the 2D array
DReshape the 2D array to (3, 1, 4) and add to the 3D array
Step-by-Step Solution
Solution:
  1. Step 1: Analyze shapes for broadcasting

    3D shape (2,3,1), 2D (3,4). NumPy automatically pads the shorter shape with 1s on the left to (1,3,4).
  2. Step 2: Check compatibility

    Compare (2,3,1) vs (1,3,4): 2 vs 1 (ok), 3 vs 3 (ok), 1 vs 4 (ok).
  3. Final Answer:

    Add directly without reshaping, broadcasting works automatically -> Option A
  4. Quick Check:

    NumPy auto-pads for broadcasting [OK]
Quick Trick: Direct addition works due to automatic padding [OK]
Common Mistakes:
  • Reshaping to incompatible shapes like (3,1,4)
  • Transposing instead of using auto-padding
  • Ignoring dimension order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes