Two signals
A sonar sends a short known pattern p = [1, 1, −1]. The receiver records 8 samples x[n]. The echo is hidden somewhere in small noise. Where is it, and how alike is it to p?
Multiply and add
Put p under the first three samples of x. Multiply each lined-up pair: 0.2·1, −0.3·1 and 0.1·(−1). Where both have the same sign, the product is positive. Opposite signs give a negative product.
Add the three products: 0.2 − 0.3 − 0.1 = −0.2. This multiply-and-add is the dot product. One number now says how alike p and this part of x are. Store it as r[0].
Slide it
Shift p one sample to the right: this shift is the lag, l = 1. Multiply the new pairs and add again: r[1] = −1.2. Negative: here x leans the opposite way to p.
Keep sliding until p reaches the end of x. Eight samples and a three-sample pattern give 8 − 3 + 1 = 6 lags. The list r[l] is the cross-correlation of x and p.
Reading the result
The biggest value is r[3] = 3.0: at lag 3, p lines up with the echo. So the echo arrived 3 samples after we started listening. Radar, sonar and GPS find delays this way.
Large and positive (r[3] = 3.0): same shape. Negative (r[1] = −1.2): leaning the opposite way. Close to zero (r[2] = 0.2): unrelated. The size also grows with loudness, so compare values from the same signals only.
Divide by the sizes of both lists: ρ = Σa·b / (√Σa² · √Σb²). The result always lies between −1 and 1. At lag 3, ρ = 0.997: almost the same shape. Loudness no longer matters.
Convolution and code
Convolution flips one signal, then slides, multiplies and adds. Correlation slides without the flip. So correlating with p equals convolving with p reversed: [−1, 1, 1]. Same numbers, −0.2, −1.2, 0.2, 3.0, −0.4, −0.8.
With numpy, np.correlate(x, p) slides, multiplies and adds for every lag where p fits (mode 'valid'). np.argmax(r) gives the index of the largest value: 3, the echo's delay in samples.
The working
# step 1/10 · question
pattern p[n] = [1, 1, −1] (3 samples)
received x[n] = [0.2, −0.3, 0.1, 1, 0.9, −1.1, 0.2, −0.1]
(8 samples)
question 1: where does p sit inside x?
question 2: how alike are they there?
one tool answers both: correlation
The pattern [1, 1, −1] is the Barker code of length 3. The received samples are made up for the example: the pattern at a delay of 3 samples plus small noise. Every number in the figure is computed from this model. Books differ in which signal they shift, so r[l] in one text can be r[−l] in another. Here r[l] = Σ x[n]·p[n − l], the convention of Proakis & Manolakis and of scipy.signal.correlate; np.correlate(x, p) gives the same values for real signals.