---
title: Vectorized arithmetic, broadcasting and masks
heading: Whole-array thinking
eyebrow: A4 · Lesson 29 · Vectorizing
xp: 40
---

::: hook
A Python loop over a million samples takes about a second. The same arithmetic written on whole NumPy arrays takes a few milliseconds, because NumPy runs the loop in compiled code. More importantly, array code reads like the math: `v = A * np.sin(2 * np.pi * f * t)` is the formula. This lesson is about writing everything that way, including the parts that look like they need a loop: clipping, conditionals, running sums and finding where something happens.
:::

::: predict
## `t = np.array([0, 1, 2])` and `f = np.array([[1], [10]])`, a column. What shape is `f * t`?

- [ ] `(3,)`
- [ ] `(2,)`
- [x] `(2, 3)`
- [ ] An error, because the shapes don't match

::: reveal
`(2, 3)`. **Broadcasting** stretches the column across the row: each of the 2 frequencies times each of the 3 times. That one product builds a whole table, like a sweep of several signals at once, without a loop.
:::
:::

::: nameit
## Elementwise everything

Arithmetic, comparisons and NumPy functions (`np.sin`, `np.exp`, `np.abs`, `np.sqrt`, ...) all act element by element:

```
v = A * np.sin(2 * np.pi * f * t)
p = v**2 / R
```

A loop like `for k in range(n): y[k] = g(x[k])` almost always becomes `y = g(x)`.

## Broadcasting

When shapes differ, NumPy lines them up from the right and stretches any dimension of size 1:
- an array and a single number: the number applies to every element;
- a row `(n,)` and a column `(m, 1)`: an `(m, n)` table.

`x[:, None]` turns a 1D array into a column. Broadcasting is how you evaluate a formula over a grid of two parameters in one line.

## Masks: conditions on arrays

A comparison gives a **boolean array**:

```
high = v > 3.0                 # array of True/False
v[high]                        # only the high samples
np.count_nonzero(high)         # how many
np.mean(high)                  # what fraction
```

Combine masks with `&` (and), `|` (or) and `~` (not), with parentheses: `(v > 1) & (v < 2)`.

## Conditionals without loops

```
np.where(v > 0, v, 0)          # half-wave rectifier: v where positive, else 0
np.clip(g * v, -L, L)          # an amplifier clipping at ±L
np.maximum(v - 0.7, 0)         # a diode drop
```

## Running sums, differences and positions

| Function | Gives |
|---|---|
| `np.cumsum(x)` | running totals |
| `np.diff(x)` | differences of neighbors (one shorter) |
| `np.argmax(x)`, `np.argmin(x)` | the index of the largest, smallest |
| `np.nonzero(mask)[0]` | the indexes where a mask is true |

`np.cumsum(i) * dt` integrates a current into charge; `np.diff(v) / dt` approximates a derivative. Lesson 39 makes both precise.
:::

::: example
## Clip a sine wave the way an amplifier with gain 3 and a ±9 V supply would, and find the fraction of time it's clipped.

::: solution
1. **Amplify and clip the whole array.** `np.clip` limits every sample to ±9 V.

```
import numpy as np
t = np.linspace(0, 0.02, 2001)
vin = 4 * np.sin(2 * np.pi * 50 * t)
vout = np.clip(3 * vin, -9, 9)
clipped = np.mean(np.abs(3 * vin) > 9)
print(vout.max(), clipped)        # 9.0, about 0.46
```

2. **The peak.** The output peaks at 9 V.
3. **The clipped fraction.** The input asks for more than 9 V whenever $|\sin| > 0.75$, which is
   $$1 - \frac{2}{\pi}\sin^{-1}0.75 = 46\%$$
   of the time.

**Answer:** the output peaks at 9 V and is clipped 46% of the time.
:::
:::

::: example
## Evaluate an RC low-pass's gain at five frequencies for three different corners, as one table.

::: solution
1. **Shape the arrays to broadcast.** The frequencies lie along a row, shape (5,), and the corners down a column, shape (3, 1).
2. **Evaluate the gain once.** Broadcasting gives a (3, 5) table.

```
f = np.array([10, 100, 1e3, 1e4, 1e5])        # shape (5,)
fc = np.array([100, 1e3, 1e4])[:, None]       # shape (3, 1)
H = 1 / np.sqrt(1 + (f / fc)**2)              # shape (3, 5)
print(np.round(H, 3))
```

3. **Read the table.** Each row is one filter, each column one frequency. Broadcasting did a 15-entry sweep with no loop.

**Answer:** one line of arithmetic gives a 3 × 5 table of gains, one row per corner and one column per frequency.
:::
:::

::: check
kind: python
given: A = 5 | 8; g = 3 | 10; L = 9 | 12

## For the sine `vin` in the starter, set `vout` to the output of an amplifier with gain `g` = {g} that clips at ±`L` = {L} V, and `frac` to the fraction of samples that are clipped (where $|g \cdot v_{in}| > L$), with no loops.

```python starter
import numpy as np
t = np.linspace(0, 0.02, 4001)
vin = A * np.sin(2 * np.pi * 50 * t)
vout = g * vin
frac = 0
print(vout.max(), frac)
```

```python solution
import numpy as np
t = np.linspace(0, 0.02, 4001)
vin = A * np.sin(2 * np.pi * 50 * t)
vout = np.clip(g * vin, -L, L)
frac = np.mean(np.abs(g * vin) > L)
print(vout.max(), frac)
```

```python tests
import numpy as np
t = np.linspace(0, 0.02, 4001)
vi = A * np.sin(2 * np.pi * 50 * t)
assert np.allclose(vout, np.clip(g * vi, -L, L)), "vout should be g·vin clipped to ±L: try np.clip."
assert abs(frac - np.mean(np.abs(g * vi) > L)) < 1e-12, "frac should be the mean of the mask |g·vin| > L."
```
:::

::: check
kind: python
given: Vd = 0.6 | 0.7; A = 3 | 10

## Set `vout` to a half-wave rectifier's output with a diode drop of `Vd` = {Vd} V: the input minus `Vd` where that's positive, otherwise 0. Then set `avg` to its mean.

```python starter
import numpy as np
t = np.linspace(0, 0.04, 8001)
vin = A * np.sin(2 * np.pi * 50 * t)
vout = vin - Vd
avg = 0
print(vout.max(), avg)
```

```python solution
import numpy as np
t = np.linspace(0, 0.04, 8001)
vin = A * np.sin(2 * np.pi * 50 * t)
vout = np.maximum(vin - Vd, 0)
avg = vout.mean()
print(vout.max(), avg)
```

```python tests
import numpy as np
t = np.linspace(0, 0.04, 8001)
vi = A * np.sin(2 * np.pi * 50 * t)
assert np.allclose(vout, np.where(vi - Vd > 0, vi - Vd, 0)), "vout should be vin − Vd where positive and 0 elsewhere: np.maximum(vin - Vd, 0)."
assert abs(avg - vout.mean()) < 1e-12, "avg should be vout.mean()."
```
:::

::: check
kind: python
given: fc = 100 | 1000; n = 3 | 5

## Using broadcasting, set `H` to a table of RC low-pass gains $1/\sqrt{1 + (f/f_c)^2}$ with one row per corner in `fcs` and one column per frequency in `f`. Then set `col` to the column for 1 kHz.

```python starter
import numpy as np
f = np.array([10, 100, 1000, 10000, 100000])
fcs = fc * np.arange(1, n + 1)
H = np.zeros((n, 5))
col = H[:, 0]
print(H.shape)
```

```python solution
import numpy as np
f = np.array([10, 100, 1000, 10000, 100000])
fcs = fc * np.arange(1, n + 1)
H = 1 / np.sqrt(1 + (f / fcs[:, None])**2)
col = H[:, 2]
print(H.shape)
```

```python tests
import numpy as np
f = np.array([10, 100, 1000, 10000, 100000])
fcs = fc * np.arange(1, n + 1)
want = 1 / np.sqrt(1 + (f[None, :] / fcs[:, None])**2)
assert H.shape == (n, 5), f"H should have shape ({n}, 5): one row per corner. Make fcs a column with fcs[:, None]."
assert np.allclose(H, want), "Some gains are wrong."
assert np.allclose(col, want[:, 2]), "col should be the column for 1 kHz, H[:, 2]."
```
:::

::: check
kind: python
given: k = 0..3 int

## For the sampled signal in the starter, set `ups` to the array of indexes `i` where it crosses zero going up (sample `i` below 0, sample `i + 1` at or above 0), with no loops, and `peak_at` to the index of its largest sample.

```python starter
import numpy as np
t = np.linspace(0, 1, 1001)
x = np.sin(2 * np.pi * (3 + k) * t + 0.3) + 0.2 * np.sin(2 * np.pi * 17 * t)
ups = np.array([])
peak_at = 0
print(ups, peak_at)
```

```python solution
import numpy as np
t = np.linspace(0, 1, 1001)
x = np.sin(2 * np.pi * (3 + k) * t + 0.3) + 0.2 * np.sin(2 * np.pi * 17 * t)
ups = np.nonzero((x[:-1] < 0) & (x[1:] >= 0))[0]
peak_at = np.argmax(x)
print(ups, peak_at)
```

```python tests
import numpy as np
t = np.linspace(0, 1, 1001)
xs = np.sin(2 * np.pi * (3 + k) * t + 0.3) + 0.2 * np.sin(2 * np.pi * 17 * t)
want = [i for i in range(len(xs) - 1) if xs[i] < 0 <= xs[i + 1]]
assert list(np.asarray(ups)) == want, "ups should be the indexes where x[:-1] < 0 and x[1:] >= 0, combined with &."
assert peak_at == int(np.argmax(xs)), "peak_at should be np.argmax(x)."
```
:::

::: check
kind: python
given: f = 1000 | 2000 | 5000; D = 0.2 | 0.35 | 0.5 | 0.8

## The starter samples a PWM signal (0 or 3.3 V) at 1 MHz for 20 periods. Using masks and no loops, set `duty` to the fraction of samples that are high, `rises` to the indexes `i` where sample `i` is low and sample `i + 1` is high, and `period` to the average spacing between rises, in seconds.

```python starter
import numpy as np
fs = 1e6
t = np.arange(int(20 * fs / f)) / fs
x = np.where((t * f) % 1 < D, 3.3, 0.0)
duty = x.mean()
rises = np.nonzero(x > 1)[0]
period = 0
print(duty, period)
```

```python solution
import numpy as np
fs = 1e6
t = np.arange(int(20 * fs / f)) / fs
x = np.where((t * f) % 1 < D, 3.3, 0.0)
high = x > 1.65
duty = high.mean()
rises = np.nonzero(~high[:-1] & high[1:])[0]
period = np.mean(np.diff(rises)) / fs
print(duty, period)
```

```python tests
import numpy as np
fs = 1e6
tt = np.arange(int(20 * fs / f)) / fs
xx = np.where((tt * f) % 1 < D, 3.3, 0.0)
h = xx > 1.65
assert abs(duty - h.mean()) < 1e-12 and abs(duty - D) < 0.01, f"duty is the fraction of samples above half of 3.3 V, about {D}."
want = np.nonzero(~h[:-1] & h[1:])[0]
assert np.array_equal(np.asarray(rises), want), "rises are the indexes where sample i is low and sample i + 1 is high."
assert abs(period - 1 / f) < 1e-6 / f * 10, f"period should be close to {1 / f:.6g} s."
```

::: right
Right. The mask `high` turns the waveform into True and False, its mean is the duty cycle, and comparing it with itself shifted by one finds the edges. Their spacing divided by the sample rate is the period.
:::
:::

::: check
kind: choice

## `a` has shape `(3,)` and `b` has shape `(4,)`. What does `a + b` do?

- [x] Raises an error: the shapes can't be broadcast together
- [ ] Gives shape `(3, 4)`
- [ ] Gives shape `(4,)`, padding `a` with a zero
- [ ] Gives shape `(7,)`, joining them

::: right
Right. Broadcasting lines shapes up from the right, and 3 against 4 neither matches nor is 1. For a table of every sum, make one a column: `a[:, None] + b` has shape `(3, 4)`.
:::

::: misses
- [2] That needs `a` as a column, `a[:, None]`. Two flat arrays of different lengths don't broadcast.
- [3] NumPy never pads silently. Mismatched lengths are an error.
- [4] `+` adds element by element. Joining arrays is `np.concatenate`.
:::
:::

::: explain
## Why is `y = np.sin(x)` on a million-element array so much faster than a Python loop calling `math.sin` a million times?

::: model
In the Python loop, every pass goes through the interpreter: fetching the next element, looking up `math.sin`, calling it, and storing the result as a separate Python object, which costs far more than the sine itself. `np.sin(x)` makes one call, and inside it a compiled loop works directly on the array's raw numbers in memory. The arithmetic is the same; the overhead per element nearly disappears.
:::
:::

::: practice

::: check
kind: python
given: lo = 1 | 2; hi = 3 | 4

## Set `n_in` to how many samples of `x` (made in the starter) lie between `lo` = {lo} and `hi` = {hi} inclusive, using a combined mask.

```python starter
import numpy as np
x = np.linspace(0, 5, 501)
n_in = 0
print(n_in)
```

```python solution
import numpy as np
x = np.linspace(0, 5, 501)
n_in = np.count_nonzero((x >= lo) & (x <= hi))
print(n_in)
```

```python tests
import numpy as np
x = np.linspace(0, 5, 501)
assert n_in == np.count_nonzero((x >= lo) & (x <= hi)), "Combine (x >= lo) & (x <= hi) and count the True values."
```
:::

::: check
kind: python
given: I = 0.5 | 2; dt = 0.001 | 0.01

## A constant current `I` = {I} A is sampled every `dt` = {dt} s for 100 samples. Set `q` to the running charge `np.cumsum(i) * dt`, and `q_end` to its last value.

```python starter
import numpy as np
i = I * np.ones(100)
q = i
q_end = 0
print(q_end)
```

```python solution
import numpy as np
i = I * np.ones(100)
q = np.cumsum(i) * dt
q_end = q[-1]
print(q_end)
```

```python tests
import numpy as np
assert np.allclose(q, np.cumsum(I * np.ones(100)) * dt), "q should be np.cumsum(i) * dt."
assert abs(q_end - 100 * I * dt) < 1e-12, "q_end should be the last running total."
```
:::
:::
