Scalar vs Row vs Column Broadcasting Practice Problem
This data science coding problem helps you practice Broadcasting & Vectorization, scalar vs row vs column broadcasting, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Broadcasting & Vectorization.
- Problem ID: 108
- Problem key: 108-scalar-vs-row-vs-column-broadcasting
- URL: https://datacrack.app/solve/108-scalar-vs-row-vs-column-broadcasting
- Difficulty: medium
- Topic: Broadcasting & Vectorization
- Module: NumPy Foundations
Problem Statement
# 🧩 Scalar vs Row vs Column Broadcasting
---
### 🎯 Goal
In data science, you frequently need to apply a **scalar**, a **row vector**, or a **column vector** to every element, row, or column of a matrix. These three patterns are the most common forms of broadcasting in practice — they appear in feature scaling, bias addition in neural networks, and column-wise normalization.
---
### 🔍 The Three Broadcasting Patterns
Given a matrix `M` of shape `(m, n)`:
| Mode | Operation | Vector Shape | What Happens |
|:-----|:----------|:-------------|:-------------|
| **scalar** | `M * s` | `()` — scalar | Every element multiplied by `s` |
| **row** | `M + v` | `(n,)` — matches columns | `v` is added to **every row** |
| **col** | `M + v.reshape(-1, 1)` | `(m, 1)` — column vector | The reshaped vector is added to each column of `M` |
```python
# Row broadcasting: (2,3) + (3,) → (2,3)
M + row_vec # row_vec applied to each row
# Column broadcasting: (2,3) + (2,1) → (2,3)
M + col_vec[:, None] # col_vec applied to each column
```
---
### 💻 Task
Implement `broadcast_operation(matrix, vector, mode)` that applies:
- `"scalar"`: multiply `matrix * vector`
- `"row"`: add `matrix + vector` (row-wise broadcast)
- `"col"`: add `matrix + vector.reshape(-1, 1)` (column-wise broadcast)
---
### 📥 Input
- `matrix`: 2D list of numbers
- `vector`: int/float (scalar) or list of numbers (1D)
- `mode`: string — `"scalar"`, `"row"`, or `"col"`
### 📤 Output
- Result as a nested Python list
---
### 🧩 Starter Code
```python
import numpy as np
def broadcast_operation(matrix, vector, mode):
"""
Apply scalar, row, or column broadcasting.
Args:
matrix (list): 2D input matrix
vector: Scalar, row vector, or column vector
mode (str): "scalar", "row", or "col"
Returns:
list: Result as a nested Python list
"""
mat = np.array(matrix, dtype=float)
vec = np.array(vector, dtype=float)
# 🧠 TODO: Handle each mode
# scalar → mat * vec
# row → mat + vec (vec shape (n,) broadcasts across rows)
# col → mat + vec.reshape(-1, 1) (vec shape (m,1) broadcasts across cols)
pass
```
---
### 💡 Example
```python
broadcast_operation([[1,2,3],[4,5,6]], 10, "scalar")
# Expected: [[10.0, 20.0, 30.0], [40.0, 50.0, 60.0]]
broadcast_operation([[1,2,3],[4,5,6]], [10,20,30], "row")
# Expected: [[11.0, 22.0, 33.0], [14.0, 25.0, 36.0]]
broadcast_operation([[1,2,3],[4,5,6]], [10,20], "col")
# Expected: [[11.0, 12.0, 13.0], [24.0, 25.0, 26.0]]
```
---
### 🔑 Key Concepts
- `v.reshape(-1, 1)` (or `v[:, None]`) converts a 1D vector `(n,)` → column vector `(n, 1)` — critical for column broadcasting
- Row broadcasting is the **default** when adding a 1D array to a 2D matrix
- Scalar broadcasting is the simplest form — every element is affected identically
- These patterns replace nested Python loops with single NumPy expressions