Skip to content

Instantly share code, notes, and snippets.

@werediver
Created September 29, 2014 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save werediver/a003604e3a275cf40e39 to your computer and use it in GitHub Desktop.
Save werediver/a003604e3a275cf40e39 to your computer and use it in GitHub Desktop.
Sample code
from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as pp
def xcorr(a, b, mode='same'):
a = np.asarray(a)
b = np.asarray(b)
a = a - a.mean()
b = b - b.mean()
r = np.correlate(a, b, mode)
r /= np.sqrt(np.correlate(a, a) * np.correlate(b, b))
return r
def xcorr_sl(a, b, k=2):
sl = k / np.sqrt(min(len(a), len(b))) # min?
return sl
def xcorr_lags(r):
lag_max = int(len(r) / 2)
lags = np.asarray(xrange(-lag_max, lag_max + len(r) % 2))
return lags
def xcorr_plot(a, b, mode='same', sl_k=2):
r = xcorr(a, b)
sl = xcorr_sl(a, b, k=sl_k)
lags =xcorr_lags(r)
pp.plot(lags, r)
pp.plot(lags, np.ones(len(lags)) * sl, color='r')
pp.plot(lags, np.ones(len(lags)) * -sl, color='r')
pp.show()
n = 100
a = np.random.normal(10, 2, n)
#b = np.random.normal(20, 5, n)
xcorr_plot(a, a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment