George
George

Reputation: 159

Calculating cross-correlation with fft returning backwards output

I'm trying to cross correlate two sets of data, by taking the fourier transform of both and multiplying the conjugate of the first fft with the second fft, before transforming back to time space. In order to test my code, I am comparing the output with the output of numpy.correlate. However, when I plot my code, (restricted to a certain window), it seems the two signals go in opposite directions/are mirrored about zero.

This is what my output looks like

My output

My code:

import numpy as np
import pyplot as plt

phl_data = np.sin(np.arange(0, 10, 0.1))
mlac_data = np.cos(np.arange(0, 10, 0.1))
N = phl_data.size
zeroes = np.zeros(N-1)
phl_data = np.append(phl_data, zeroes)
mlac_data = np.append(mlac_data, zeroes)

# cross-correlate x = phl_data, y = mlac_data:
# take FFTs:
phl_fft = np.fft.fft(phl_data)
mlac_fft = np.fft.fft(mlac_data)
# fft of cross-correlation
Cw = np.conj(phl_fft)*mlac_fft
#Cw = np.fft.fftshift(Cw)
# transform back to time space:
Cxy = np.fft.fftshift(np.fft.ifft(Cw))
times = np.append(np.arange(-N+1, 0, dt),np.arange(0, N, dt))

plt.plot(times, Cxy)
plt.xlim(-250, 250)

# test against convolving:
c = np.correlate(phl_data, mlac_data, mode='same')
plt.plot(times, c)
plt.show()

(both data sets have been padded with N-1 zeroes)

Upvotes: 1

Views: 1184

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60484

The documentation to numpy.correlate explains this:

This function computes the correlation as generally defined in signal processing texts:

c_{av}[k] = sum_n a[n+k] * conj(v[n])

and:

Notes

The definition of correlation above is not unique and sometimes correlation may be defined differently. Another common definition is:

c'_{av}[k] = sum_n a[n] conj(v[n+k])

which is related to c_{av}[k] by c'_{av}[k] = c_{av}[-k].

Thus, there is not a unique definition, and the two common definitions lead to a reversed output.

Upvotes: 1

Related Questions