A4 · Lesson 29 · Vectorizing
Whole-array thinking
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?
(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.
Name it
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.
Worked 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.
Show the solution
- Amplify and clip the whole array.
np.cliplimits 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
- The peak. The output peaks at 9 V.
- The clipped fraction. The input asks for more than 9 V whenever , which is of the time.
Answer the output peaks at 9 V and is clipped 46% of the time.
Worked example
Evaluate an RC low-pass's gain at five frequencies for three different corners, as one table.
Show the solution
- Shape the arrays to broadcast. The frequencies lie along a row, shape (5,), and the corners down a column, shape (3, 1).
- 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))
- 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
For the sine vin in the starter, set vout to the output of an amplifier with gain g = 3 that clips at ±L = 12 V, and frac to the fraction of samples that are clipped (where ), with no loops.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Set vout to a half-wave rectifier's output with a diode drop of Vd = 0.6 V: the input minus Vd where that's positive, otherwise 0. Then set avg to its mean.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Using broadcasting, set H to a table of RC low-pass gains with one row per corner in fcs and one column per frequency in f. Then set col to the column for 1 kHz.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
a has shape (3,) and b has shape (4,). What does a + b do?
Explain why
Why is y = np.sin(x) on a million-element array so much faster than a Python loop calling math.sin a million times?
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
Keep practicing
7 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.