Slide a shape across a signal.
Nearly everything that is done to a signal, from smoothing a shaky line to finding a satellite, is built on one small operation. This chapter goes through that operation slowly enough for you to follow every number.
The operation works on a signal, and since that word appears on every page of this site, it is worth a moment before anything else. Suppose you wrote down the temperature outside your window once every hour for a week. You would end up with a long row of numbers, in the order you measured them, and that row of numbers is a signal. The height of a radio wave measured a million times a second is a signal too, and so is the number of pages you read each day. If you mark each number as a dot on a chart, with the first at the left and the last at the right, and join the dots, the signal becomes a line that rises and falls. Most of the charts on this site are lines of that kind.
You have very likely met the operation already, under the name of the seven-day average. Numbers that are counted every day bounce around, whether they are temperatures, sales in a shop or visitors to a park, because each day's figure is partly real change and partly luck. To see where things are heading, you take each day together with the six days before it, add the seven numbers, and divide by seven. When you do that for every day in turn, you get a second line that follows the first and is much smoother.
Look closely at what the seven-day average does. It slides a window along the row of numbers, and at each stop it treats the seven numbers inside the window equally. Now suppose each place in the window is given its own weight, which is a number that says how much the value in that place should count. Each value in the window is multiplied by the weight of its place, and the results are added together. A school grade is worked out this way when the final exam counts for more than a quiz. Some places in the window can count for more and some for less, and a place can even be given a negative weight, so that its value is subtracted from the total.
Drawn as a small chart of its own, a list of weights has a shape, and that shape is what this chapter is named for. Different shapes do different jobs. Equal weights smooth the signal, as the seven-day average does. Weights that are negative on the left half and positive on the right half subtract what came before from what comes after. Where the signal is steady the two halves cancel and the result is zero, and where the signal suddenly jumps the result is large, so a shape like this finds edges. And weights that copy a pattern you are searching for give their largest result at the place where that pattern occurs, which is the subject of the next chapter.
Pick a signal and a shape below, then drag the shape across the signal. Four charts show what happens. The first is the signal, with the shape drawn over it wherever you have put it. The second is the shape by itself, as a row of weights. The third shows each signal value under the shape multiplied by the weight above it. Add those results together and you have a single number, and that number becomes one point of the fourth chart. Slide the shape from one end of the signal to the other and the fourth chart fills in.
Two of the controls need a word of explanation. The noise slider adds random wobble to the signal, of the kind every real measurement carries, so you can see how each shape copes with it. The dashed line across the last chart is a level you can drag up and down. Wherever the result rises above that level, the page marks the spot. Deciding where to put such a line is a large part of the next chapter.
The loop this is all the page does
Written as a program, the whole chapter is two loops, one inside the other. A loop is an instruction to do the same thing again and again. The outer loop moves the shape along the signal, one position at a time. The inner loop multiplies each weight by the signal value under it and adds up the results. In the programs below, x is the signal, h is the list of weights and y is the result.
Two names are worth knowing, because you will meet them in every book on the subject. Sliding a shape across a signal exactly as described here is called correlation. If the shape is first turned end for end and then slid across, the operation is called convolution. The checkbox above does the turning. For a shape that reads the same in both directions, such as the equal weights, the two give identical results.
/* Slide a list of weights h across a signal x. One result per position.
The shape is centered on each position, so the result lines up with the signal. */
void correlate(const float *x, int n, const float *h, int taps, float *y)
{
int half = taps / 2;
for (int pos = 0; pos < n; pos++) {
float sum = 0.0f;
for (int k = 0; k < taps; k++) {
int i = pos + k - half; /* which signal value sits under weight k */
if (i >= 0 && i < n) sum += h[k] * x[i];
}
y[pos] = sum;
}
}#include <span>
#include <vector>
// Slide a list of weights h across a signal x. One result per position.
std::vector<float> correlate(std::span<const float> x, std::span<const float> h)
{
const int n = x.size(), taps = h.size(), half = taps / 2;
std::vector<float> y(n, 0.0f);
for (int pos = 0; pos < n; pos++) {
float sum = 0.0f;
for (int k = 0; k < taps; k++) {
int i = pos + k - half;
if (i >= 0 && i < n) sum += h[k] * x[i];
}
y[pos] = sum;
}
return y;
}/// Slide a list of weights h across a signal x. One result per position.
pub fn correlate(x: &[f32], h: &[f32]) -> Vec<f32> {
let half = (h.len() / 2) as isize;
(0..x.len() as isize)
.map(|pos| {
h.iter().enumerate().map(|(k, &hk)| {
let i = pos + k as isize - half;
if i >= 0 && (i as usize) < x.len() { hk * x[i as usize] } else { 0.0 }
}).sum()
})
.collect()
}import numpy as np
def correlate(x, h):
"""Slide the weights h across the signal x. One result per position."""
n, taps = len(x), len(h)
half = taps // 2
y = np.zeros(n)
for pos in range(n):
for k in range(taps):
i = pos + k - half
if 0 <= i < n:
y[pos] += h[k] * x[i]
return y
# the same thing, the way you would really write it:
y = np.correlate(x, h, mode="same")