Qu

xcorr

Builtin index · Signal processing

result = xcorr(x, [y])

Input: x, y · Output: result

What it is

x is a length-N vector; y (optional length-M vector, defaults to x for autocorrelation).

Overloads

One call shape — this function is not overloaded.

CodeInputOutputDescription
result = xcorr(x, [y])
x vectorx is a length-N vector.
y vector, optionaly (optional length-M vector, defaults to x for autocorrelation).
result vector
Returns a length-N+M-1 vector, the full lag range (zero lag at the middle for equal-length inputs).

Examples

From the documentation, and run by the build -- the output and the figure below are what the engine actually produced. Simplest first.

  r = xcorr(x)             # autocorrelation

  lag = xcorr(a, b)        # cross-correlation between two signals

from numerics-dsp

N = 200
Fs = 200
t = (0 to N - 1) / Fs
x = sin(2*pi*10*t)
shift = 15
y = zeros(N)
y[shift:N-1] = x[0:N-1-shift]

c = corr(x, x)
print("corr(x, x) = {c}")
c2 = corr(x, y)
print("corr(x, y) (shifted copy) = {c2:.4f}")

r = xcorr(x, y)
print("length(xcorr) = {length(r)} (expect 2N-1 = {2*N-1})")
zero_lag_idx = N - 1
best_idx = where r == max(r)
best_lag = best_idx[0] - zero_lag_idx
print("Best-match lag (samples): {best_lag} (true shift was {shift})")

from tour

How it works

xcorr(x, [y]) — cross-correlation (or autocorrelation, when y is omitted), full lag range (length(x)+length(y)-1 values, zero lag at the middle for equal-length inputs).

From the note above this builtin in the interpreter, where the reasoning was written down as it was built.