Python

NumPy Correlate()

The correlate() function in NumPy determines the cross-correlation of two one-dimensional sequences.

According to the official NumPy docs, the correlate() function calculates the correlation as defined in signal processing texts:

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

In more simplistic terms, cross-correlation refers to the measurement of the similarities between two sequences as a function of the displacement of one series relative to one another.

You can appreciate the math and logic behind cross-correlation in the resource below:

https://en.wikipedia.org/wiki/Cross-correlation

Function Syntax

For now, let us focus on the correlate() function in NumPy and its workings

The function syntax is as depicted below:

1
numpy.correlate(a, v, mode='valid')

The function parameters are as follows:

  1. a, v – refers to the input sequences.
  2. mode – refers to the convolution mode—defaults to valid. You can learn more about convolution in the official NumPy convolve function and Wikipedia Convolution.

Return Value

The function will then return the discrete cross-correlation value of the input sequences.

Example #1

Take the example below that shows how to use the correlate() function to determine the cross-correlation of two sequences.

1
2
3
4
5
6
# import numpy
import numpy as np
a = np.array([1,2,3])
v = np.array([1., 2, 3.3])

print(np.correlate(a, v))

The example above should return a cross-correlation value as shown:

1
[14.9]

Example #2

To specify the convolution mode, we can do:

1
2
3
a = np.array([1,2,3])
v = np.array([1., 2, 3.3])
print(np.correlate(a, v, 'same'))

The code above should return the cross-correlation using the ‘same’ convolution mode.

1
[ 8.6 14.9  8. ]

Example #3

For the ‘full’ convolution mode, the example above should return:

1
2
3
a = np.array([1,2,3])
v = np.array([1., 2, 3.3])
print(np.correlate(a, v, 'full'))

Output:

1
[ 3.3  8.6 14.9  8.   3. ]

Conclusion

This guide gives the fundamentals of working with the correlate() function in NumPy. Feel free to explore the docs for more.

Happy coding!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list