├── README.md └── xcorr.py /README.md: -------------------------------------------------------------------------------- 1 | # xcorr_python 2 | Cross-correlation coefficients in Python 3 | 4 | Returns coefficients (or inner product) and lags 5 | 6 | This might save someone a bit of time, I could not find a standard xcorr function (like MATLAB's) in Python, which returns the *coefficients* of a cross correlation of two signals (instead of the inner product). 7 | 8 | This code is adapted from [matplotlib's xcorr function](https://matplotlib.org/examples/pylab_examples/xcorr_demo.html "matplotlib xcorr()"), I just separated the normalization from the plotting behavior. 9 | 10 | Calls [numpy.correlate(x,y, mode='full')](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.correlate.html "numpy.correlate()") 11 | 12 | #### This is the necessary transformation function (inner product -> coeffs.) 13 | n = np.sqrt(np.dot(x, x) * np.dot(y, y)) 14 | 15 | coeffs = np.true_divide(innerproduct,n) 16 | -------------------------------------------------------------------------------- /xcorr.py: -------------------------------------------------------------------------------- 1 | def xcorr(x, y, normed=True, detrend=False, maxlags=10): 2 | # Cross correlation of two signals of equal length 3 | # Returns the coefficients when normed=True 4 | # Returns inner products when normed=False 5 | # Usage: lags, c = xcorr(x,y,maxlags=len(x)-1) 6 | # Optional detrending e.g. mlab.detrend_mean 7 | 8 | Nx = len(x) 9 | if Nx != len(y): 10 | raise ValueError('x and y must be equal length') 11 | 12 | if detrend: 13 | import matplotlib.mlab as mlab 14 | x = mlab.detrend_mean(np.asarray(x)) # can set your preferences here 15 | y = mlab.detrend_mean(np.asarray(y)) 16 | 17 | c = np.correlate(x, y, mode='full') 18 | 19 | if normed: 20 | n = np.sqrt(np.dot(x, x) * np.dot(y, y)) # this is the transformation function 21 | c = np.true_divide(c,n) 22 | 23 | if maxlags is None: 24 | maxlags = Nx - 1 25 | 26 | if maxlags >= Nx or maxlags < 1: 27 | raise ValueError('maglags must be None or strictly ' 28 | 'positive < %d' % Nx) 29 | 30 | lags = np.arange(-maxlags, maxlags + 1) 31 | c = c[Nx - 1 - maxlags:Nx + maxlags] 32 | return lags, c 33 | --------------------------------------------------------------------------------