---
title: Two-dimensional arrays
heading: Tables, grids and matrices
eyebrow: A4 · Lesson 30 · Two-dimensional arrays
xp: 40
---

::: hook
A data logger records eight channels at once: a table with a row per sample and a column per channel. A design sweep tries every combination of R and C: a grid. A circuit's node equations are a matrix. All three are two-dimensional arrays, and NumPy handles them with the same whole-array style as 1D ones, plus one new idea: the **axis**, which says whether an operation runs down the rows or across the columns.
:::

::: predict
## `X` has shape `(1000, 8)`: 1000 samples of 8 channels. What shape is `X.mean(axis=0)`?

- [ ] `(1000,)`
- [x] `(8,)`
- [ ] `()`, a single number
- [ ] `(1000, 8)`

::: reveal
`(8,)`: one mean per channel. `axis=0` means "collapse the rows", averaging down each column. `axis=1` would average across each row, giving one value per sample, shape `(1000,)`. With no axis, you get a single mean of everything.
:::
:::

::: nameit
## Shape, indexing and slicing

```
X = np.array([[1, 2, 3],
              [4, 5, 6]])     # shape (2, 3): 2 rows, 3 columns
X[1, 2]                       # 6: row 1, column 2
X[0]                          # [1, 2, 3]: the first row
X[:, 1]                       # [2, 5]: the second column
X.T                           # the transpose, shape (3, 2)
X.reshape(3, 2)               # same numbers, new shape
```

## Reducing along an axis

`sum`, `mean`, `max`, `min`, `std` and `argmax` all take `axis=`:
- `axis=0` works down the rows, leaving one value per column;
- `axis=1` works across the columns, leaving one value per row.

## Grids for sweeps

`np.meshgrid` turns two 1D ranges into 2D grids, one value of each parameter at every point:

```
R = np.array([1e3, 2.2e3, 4.7e3, 10e3])
C = np.array([10e-9, 47e-9, 100e-9])
RR, CC = np.meshgrid(R, C)          # both shape (3, 4)
fc = 1 / (2 * np.pi * RR * CC)      # corner for every combination
```

Broadcasting with `R[None, :]` and `C[:, None]` does the same thing without making the grids.

To find the best combination, take the `argmin` of the whole grid and turn the flat index back into a row and column:

```
i = np.argmin(np.abs(fc - 1000))
row, col = np.unravel_index(i, fc.shape)
best = (R[col], C[row])
```

## Matrices

A 2D array is also a matrix. `A @ x` is matrix-vector multiplication, and `np.linalg.solve(A, b)` solves $A\mathbf{x} = \mathbf{b}$. Lesson 37 and A7 use these for circuit equations.
:::

::: example
## A logger recorded 4 channels at 5 samples. Find each channel's mean and the sample where channel 2 peaked.

::: solution
1. **Average down the columns.** `axis=0` gives each channel's mean.
2. **Find channel 2's peak.** Column 2 is `X[:, 2]`.

```
X = np.array([[3.30, 5.01, 1.20, 0.00],
              [3.31, 4.99, 1.80, 0.10],
              [3.29, 5.02, 2.40, 0.05],
              [3.30, 5.00, 2.10, 0.00],
              [3.30, 4.98, 1.50, 0.08]])
print(X.mean(axis=0))          # [3.3, 5.0, 1.8, 0.046]
print(np.argmax(X[:, 2]))      # 2
```

3. **Read the peak.** Channel 2's peak, 2.40, is at sample 2.

**Answer:** the channel means are 3.3, 5.0, 1.8 and 0.046, and channel 2 peaks at sample 2.
:::
:::

::: example
## From the E6 resistors 1 kΩ to 6.8 kΩ and capacitors 10 nF to 68 nF, which pair gives a corner closest to 5 kHz?

::: solution
1. **Find the time constant needed.**
   $$\begin{aligned} RC &= \frac{1}{2\pi \times 5\ \text{kHz}} \\ &= 31.8\ \mu\text{s} \end{aligned}$$
2. **Compute every pair at once.** All 36 combinations are computed at once, and `unravel_index` turns the best one's position back into a choice of parts.

```
E6 = np.array([1.0, 1.5, 2.2, 3.3, 4.7, 6.8])
R, C = E6 * 1e3, E6 * 10e-9
fc = 1 / (2 * np.pi * R[None, :] * C[:, None])    # rows: C, columns: R
row, col = np.unravel_index(np.argmin(np.abs(fc - 5000)), fc.shape)
print(R[col], C[row], fc[row, col])
```

3. **Find the nearest product.** The nearest product on offer is 33 µs, and four pairs give it: 1 kΩ with 33 nF, 1.5 kΩ with 22 nF, 2.2 kΩ with 15 nF and 3.3 kΩ with 10 nF.
4. **Its corner.** All four give a corner of 4.82 kHz. `argmin` returns one of them; any is as good as another.

**Answer:** any of the four pairs with $RC = 33$ µs, such as 1 kΩ with 33 nF, gives 4.82 kHz, the closest to 5 kHz.
:::
:::

::: check
kind: python
given: k = 1..9 int

## The starter makes `X`, 200 samples of 5 channels. Set `means` to each channel's mean, `rms` to each channel's RMS ($\sqrt{\text{mean of squares}}$), and `loudest` to the index of the channel with the largest RMS.

```python starter
import numpy as np
rng = np.random.default_rng(k)
X = rng.normal(0, 1, (200, 5)) * np.array([1, 2, 0.5, 3, 1.5]) + np.array([0, 1, 0, -1, 2])
means = X.mean()
rms = 0
loudest = 0
print(means, rms, loudest)
```

```python solution
import numpy as np
rng = np.random.default_rng(k)
X = rng.normal(0, 1, (200, 5)) * np.array([1, 2, 0.5, 3, 1.5]) + np.array([0, 1, 0, -1, 2])
means = X.mean(axis=0)
rms = np.sqrt(np.mean(X**2, axis=0))
loudest = int(np.argmax(rms))
print(means, rms, loudest)
```

```python tests
import numpy as np
rng = np.random.default_rng(k)
Xs = rng.normal(0, 1, (200, 5)) * np.array([1, 2, 0.5, 3, 1.5]) + np.array([0, 1, 0, -1, 2])
assert np.shape(means) == (5,) and np.allclose(means, Xs.mean(axis=0)), "means should be one per channel: X.mean(axis=0)."
assert np.allclose(rms, np.sqrt(np.mean(Xs**2, axis=0))), "rms should be √(mean of X²) down each column."
assert loudest == int(np.argmax(np.sqrt(np.mean(Xs**2, axis=0)))), "loudest should be the argmax of rms."
```
:::

::: check
kind: python
given: target = 500 | 2000 | 5000 | 20000

## For every pair of E6 resistor (100 Ω to 680 kΩ) and capacitor (1 nF to 6.8 µF) in the starter, compute the corner frequency as a 2D array `fc` (rows for capacitors, columns for resistors). Set `R_best`, `C_best` to the pair whose corner is nearest `target` = {target} Hz in ratio (smallest $|\log(f_c/\text{target})|$).

```python starter
import numpy as np
E6 = np.array([1.0, 1.5, 2.2, 3.3, 4.7, 6.8])
R = np.concatenate([E6 * 10**d for d in range(2, 6)])
C = np.concatenate([E6 * 10.0**d for d in range(-9, -6)])
fc = None
R_best = C_best = 0
print(R_best, C_best)
```

```python solution
import numpy as np
E6 = np.array([1.0, 1.5, 2.2, 3.3, 4.7, 6.8])
R = np.concatenate([E6 * 10**d for d in range(2, 6)])
C = np.concatenate([E6 * 10.0**d for d in range(-9, -6)])
fc = 1 / (2 * np.pi * R[None, :] * C[:, None])
row, col = np.unravel_index(np.argmin(np.abs(np.log(fc / target))), fc.shape)
R_best, C_best = R[col], C[row]
print(R_best, C_best)
```

```python tests
import numpy as np
E6 = np.array([1.0, 1.5, 2.2, 3.3, 4.7, 6.8])
R = np.concatenate([E6 * 10**d for d in range(2, 6)])
C = np.concatenate([E6 * 10.0**d for d in range(-9, -6)])
f2 = 1 / (2 * np.pi * R[None, :] * C[:, None])
assert fc is not None and np.shape(fc) == (len(C), len(R)) and np.allclose(fc, f2), "fc should have a row per capacitor and a column per resistor: use R[None, :] and C[:, None]."
best = np.min(np.abs(np.log(f2 / target)))
got = abs(np.log(1 / (2 * np.pi * R_best * C_best) / target))
assert abs(got - best) < 1e-9, "That pair isn't the closest. Use np.argmin on the whole grid and np.unravel_index."
```
:::

::: check
kind: python
given: n = 3 | 4 | 6

## Set `M` to the `n` × `n` array ({n} × {n}) whose entry at row `i`, column `j` is $1/(i + j + 1)$, using broadcasting (no loops). Then set `diag` to its diagonal and `col_sums` to the sum of each column.

```python starter
import numpy as np
M = np.zeros((n, n))
diag = col_sums = None
print(M)
```

```python solution
import numpy as np
i = np.arange(n)
M = 1 / (i[:, None] + i[None, :] + 1)
diag = np.diag(M)
col_sums = M.sum(axis=0)
print(M)
```

```python tests
import numpy as np
i = np.arange(n)
want = 1 / (i[:, None] + i[None, :] + 1)
assert np.allclose(M, want), "Entry (i, j) is 1/(i + j + 1): make i a column and j a row."
assert np.allclose(diag, np.diag(want)), "diag should be np.diag(M)."
assert np.allclose(col_sums, want.sum(axis=0)), "col_sums should be M.sum(axis=0)."
```
:::

::: check
kind: python
given: k = 1..5 int; n = 5 | 7 | 9

## The starter makes `T`, an `n` × `n` grid of temperatures ({n} × {n}). Using slices and no loops, set `inner` to the grid without its outer border, and `avg4` to the average of each inner point's four neighbors (up, down, left and right), an array the same shape as `inner`.

```python starter
import numpy as np
T = np.random.default_rng(k).uniform(20, 80, (n, n))
inner = T
avg4 = T
print(avg4)
```

```python solution
import numpy as np
T = np.random.default_rng(k).uniform(20, 80, (n, n))
inner = T[1:-1, 1:-1]
avg4 = (T[:-2, 1:-1] + T[2:, 1:-1] + T[1:-1, :-2] + T[1:-1, 2:]) / 4
print(avg4)
```

```python tests
import numpy as np
G = np.random.default_rng(k).uniform(20, 80, (n, n))
assert np.shape(inner) == (n - 2, n - 2) and np.allclose(inner, G[1:-1, 1:-1]), "inner is T[1:-1, 1:-1]."
want = np.array([[(G[i - 1, j] + G[i + 1, j] + G[i, j - 1] + G[i, j + 1]) / 4 for j in range(1, n - 1)] for i in range(1, n - 1)])
assert np.shape(avg4) == (n - 2, n - 2) and np.allclose(avg4, want), "avg4 adds the four shifted views of T, each the inner shape, and divides by 4."
```

::: right
Right. Each neighbor is the same inner block shifted by one row or column, so four slices give all the neighbors at once. Replacing each point by that average over and over is how lab A9's Laplace solver works.
:::
:::

::: check
kind: python
given: k = 1..4 int; m = 3 | 4

## An ADC sends `m` = {m} channels interleaved: channel 0's sample, then channel 1's, and so on, then channel 0 again. The starter's `data` holds 200 rounds of them. Set `X` to the samples as one row per round and one column per channel, and `p2p` to each channel's peak-to-peak value (its maximum minus its minimum).

```python starter
import numpy as np
rng = np.random.default_rng(k)
data = (np.arange(200 * m) % m + 1) * rng.uniform(-1, 1, 200 * m)
X = data
p2p = data.max() - data.min()
print(p2p)
```

```python solution
import numpy as np
rng = np.random.default_rng(k)
data = (np.arange(200 * m) % m + 1) * rng.uniform(-1, 1, 200 * m)
X = data.reshape(-1, m)
p2p = X.max(axis=0) - X.min(axis=0)
print(p2p)
```

```python tests
import numpy as np
rng = np.random.default_rng(k)
d = (np.arange(200 * m) % m + 1) * rng.uniform(-1, 1, 200 * m)
assert np.shape(X) == (200, m) and np.array_equal(X[:, 1], d[1::m]), "X should have a row per round and a column per channel: data.reshape(-1, m)."
assert np.allclose(p2p, d.reshape(-1, m).max(axis=0) - d.reshape(-1, m).min(axis=0)), "p2p is one value per channel: max minus min down each column."
```

::: right
Right. `reshape(-1, m)` deals the stream into rows of `m`, so each column is one channel, and `axis=0` reduces down the columns. `data[1::m]` would pull out channel 1 directly.
:::
:::

::: check
kind: choice

## `X` has shape `(100, 8)`. What is the shape of `X[:, 1:3]`?

- [x] `(100, 2)`
- [ ] `(100, 3)`
- [ ] `(2, 8)`
- [ ] `(100,)`

::: right
Right. `:` keeps all 100 rows, and `1:3` takes columns 1 and 2, stopping before 3.
:::

::: misses
- [2] A slice stops before its end, so `1:3` is columns 1 and 2.
- [3] The first index picks rows, and `:` keeps all of them. The slice is on the columns.
- [4] A slice keeps the dimension even if it's short. Only a single index like `X[:, 1]` drops it.
:::
:::

::: explain
## For an array of shape (samples, channels), what's the difference between `X.mean(axis=0)` and `X.mean(axis=1)`?

::: model
`axis=0` collapses the first dimension, the samples, so it averages down each column and gives one mean per channel. `axis=1` collapses the second dimension, the channels, so it averages across each row and gives one value per sample, the average of all the channels at that moment. The axis you name is the one that disappears.
:::
:::

::: practice

::: check
kind: python
given: r = 2 | 3 | 4; c = 3 | 5

## Set `A` to `np.arange(r * c)` reshaped into `r` = {r} rows and `c` = {c} columns, and `last_col` to its last column.

```python starter
import numpy as np
A = np.arange(r * c)
last_col = None
print(A)
```

```python solution
import numpy as np
A = np.arange(r * c).reshape(r, c)
last_col = A[:, -1]
print(A)
```

```python tests
import numpy as np
assert np.shape(A) == (r, c) and np.array_equal(A, np.arange(r * c).reshape(r, c)), "Reshape to (r, c)."
assert np.array_equal(last_col, np.arange(r * c).reshape(r, c)[:, -1]), "last_col is A[:, -1]."
```
:::

::: check
kind: python
given: k = 1..5 int

## Set `row_max` to the largest value in each row of `X`, and `where` to the column where each row's maximum is.

```python starter
import numpy as np
X = np.random.default_rng(k).integers(0, 100, (4, 6))
row_max = where = None
print(X)
```

```python solution
import numpy as np
X = np.random.default_rng(k).integers(0, 100, (4, 6))
row_max = X.max(axis=1)
where = X.argmax(axis=1)
print(X)
```

```python tests
import numpy as np
Xs = np.random.default_rng(k).integers(0, 100, (4, 6))
assert np.array_equal(row_max, Xs.max(axis=1)), "Use X.max(axis=1): across each row."
assert np.array_equal(where, Xs.argmax(axis=1)), "Use X.argmax(axis=1)."
```
:::
:::
