Lesson 14 of 15

Cross-Correlation

Cross-Correlation

Cross-correlation measures the similarity between two signals as a function of time lag. It is used in radar, sonar, communications, and audio fingerprinting.

Definition

The normalized cross-correlation at lag \ell for periodic signals of length NN:

Rxy[]=1Nn=0N1x[n]y[(n+)modN]R_{xy}[\ell] = \frac{1}{N} \sum_{n=0}^{N-1} x[n] \cdot y[(n + \ell) \bmod N]

The modulo wraps around the signal, treating it as periodic (circular cross-correlation).

Autocorrelation

The autocorrelation of a signal with itself:

Rxx[]=1Nn=0N1x[n]x[(n+)modN]R_{xx}[\ell] = \frac{1}{N} \sum_{n=0}^{N-1} x[n] \cdot x[(n + \ell) \bmod N]

At lag 00, autocorrelation equals signal power. It is symmetric: Rxx[]=Rxx[]R_{xx}[\ell] = R_{xx}[-\ell].

Applications

  • Time delay estimation: find the lag where RxyR_{xy} is maximized to locate a signal source
  • Pitch detection: autocorrelation peaks at lags corresponding to the period
  • Pattern matching: cross-correlate a template with a signal to find occurrences

Example

x=[1,1,1,1]x = [1, 1, -1, -1], y=[1,1,1,1]y = [1, 1, -1, -1] (same signal):

  • Lag 0: (11+11+(1)(1)+(1)(1))/4=4/4=1.0(1\cdot1 + 1\cdot1 + (-1)(-1) + (-1)(-1))/4 = 4/4 = 1.0
  • Lag 1: (11+1(1)+(1)(1)+(1)1)/4=0/4=0.0(1\cdot1 + 1\cdot(-1) + (-1)(-1) + (-1)\cdot1)/4 = 0/4 = 0.0
  • Lag 2: (1(1)+1(1)+(1)1+(1)1)/4=4/4=1.0(1\cdot(-1) + 1\cdot(-1) + (-1)\cdot1 + (-1)\cdot1)/4 = -4/4 = -1.0

Your Task

Implement:

  • xcorr(x, y, lag) — normalized circular cross-correlation at lag \ell
  • autocorrelation(x, lag) — calls xcorr(x, x, lag)
def xcorr(x, y, lag):
    N = len(x)
    return sum(x[n] * y[(n + lag) % N] for n in range(N)) / N

def autocorrelation(x, lag):
    return xcorr(x, x, lag)
Python runtime loading...
Loading...
Click "Run" to execute your code.