i have 2 dimensional array, i.e. array of sequences arrays. each sequence calculate autocorrelation, (5,4) array, 5 results, or array of dimension (5,7).
i know loop on first dimension, that's slow , last resort. there way?
thanks!
edit:
based on chosen answer plus comment mtrw, have following function:
def xcorr(x): """fft based autocorrelation function, faster numpy.correlate""" # x supposed array of sequences, of shape (totalelements, length) fftx = fft(x, n=(length*2-1), axis=1) ret = ifft(fftx * np.conjugate(fftx), axis=1) ret = fftshift(ret, axes=1) return ret
note length global variable in code, sure declare it. didn't restrict result real numbers, since need take account complex numbers well.
using fft-based autocorrelation:
import numpy numpy.fft import fft, ifft data = numpy.arange(5*4).reshape(5, 4) print data ##[[ 0 1 2 3] ## [ 4 5 6 7] ## [ 8 9 10 11] ## [12 13 14 15] ## [16 17 18 19]] dataft = fft(data, axis=1) dataac = ifft(dataft * numpy.conjugate(dataft), axis=1).real print dataac ##[[ 14. 8. 6. 8.] ## [ 126. 120. 118. 120.] ## [ 366. 360. 358. 360.] ## [ 734. 728. 726. 728.] ## [ 1230. 1224. 1222. 1224.]]
i'm little confused statement answer having dimension (5, 7), maybe there's important i'm not understanding.
edit: @ suggestion of mtrw, padded version doesn't wrap around:
import numpy numpy.fft import fft, ifft data = numpy.arange(5*4).reshape(5, 4) padding = numpy.zeros((5, 3)) datapadded = numpy.concatenate((data, padding), axis=1) print datapadded ##[[ 0. 1. 2. 3. 0. 0. 0. 0.] ## [ 4. 5. 6. 7. 0. 0. 0. 0.] ## [ 8. 9. 10. 11. 0. 0. 0. 0.] ## [ 12. 13. 14. 15. 0. 0. 0. 0.] ## [ 16. 17. 18. 19. 0. 0. 0. 0.]] dataft = fft(datapadded, axis=1) dataac = ifft(dataft * numpy.conjugate(dataft), axis=1).real print numpy.round(dataac, 10)[:, :4] ##[[ 14. 8. 3. 0. 0. 3. 8.] ## [ 126. 92. 59. 28. 28. 59. 92.] ## [ 366. 272. 179. 88. 88. 179. 272.] ## [ 734. 548. 363. 180. 180. 363. 548.] ## [ 1230. 920. 611. 304. 304. 611. 920.]]
there must more efficient way this, because autocorrelation symmetric , don't take advantage of that.
Comments
Post a Comment