NumPy: Compute cross-correlation of two given arrays
9. Cross-Correlation of Two Arrays
Write a NumPy program to compute cross-correlation of two given arrays.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating an array 'x' containing elements [0, 1, 3]
x = np.array([0, 1, 3])
# Creating an array 'y' containing elements [2, 4, 5]
y = np.array([2, 4, 5])
# Displaying the original array 'x'
print("\nOriginal array1:")
print(x)
# Displaying the original array 'y'
print("\nOriginal array1:")
print(y)
# Calculating the cross-correlation of arrays 'x' and 'y' using np.correlate()
print("\nCross-correlation of the said arrays:\n", np.correlate(x, y))
Sample Output:
Original array1: [0 1 3] Original array1: [2 4 5] Cross-correlation of the said arrays: [19]
Explanation:
In the above exercise –
x = np.array([0, 1, 3]): Create a NumPy array x with the values [0, 1, 3].
y = np.array([2, 4, 5]): Create a NumPy array y with the values [2, 4, 5].
print(np.correlate(x, y)): Compute and print the cross-correlation of the sequences x and y using np.correlate.
For more Practice: Solve these Related Problems:
- Write a function that computes the cross-correlation of two 1D arrays using np.correlate and returns the correlation vector.
- Create a program that calculates cross-correlation at different lags and identifies the lag with the maximum correlation.
- Implement a solution that normalizes the cross-correlation result to obtain correlation coefficients between -1 and 1.
- Develop a method that handles arrays of different lengths by zero-padding the shorter array before computing cross-correlation.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.Previous: Write a NumPy program to compute the covariance matrix of two given arrays.
Next: Write a NumPy program to compute pearson product-moment correlation coefficients of two given arrays.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics