Complete the code to compute the correlation of a signal with itself using numpy.
import numpy as np signal = np.array([1, 2, 3, 4, 5]) correlation = np.correlate(signal, signal, [1]) print(correlation)
The np.correlate function with mode "full" returns the complete cross-correlation, including all lags.
Complete the code to compute the cross-correlation between two signals using numpy.
import numpy as np signal1 = np.array([1, 2, 3]) signal2 = np.array([0, 1, 0.5]) cross_corr = np.correlate(signal1, signal2, [1]) print(cross_corr)
Using mode "full" computes the cross-correlation at all lags between the two signals.
Fix the error in the code to compute normalized cross-correlation between two signals.
import numpy as np signal1 = np.array([1, 2, 3, 4]) signal2 = np.array([0, 1, 0, 1]) correlation = np.correlate(signal1 - np.mean(signal1), signal2 - np.mean(signal2), [1]) normalization = np.std(signal1) * np.std(signal2) * len(signal1) normalized_corr = correlation / normalization print(normalized_corr)
The "valid" mode returns correlation only where the signals fully overlap, which is appropriate for normalized cross-correlation.
Fill both blanks to create a dictionary of cross-correlation values for lags from -2 to 2.
import numpy as np signal1 = np.array([1, 2, 3, 4, 5]) signal2 = np.array([5, 4, 3, 2, 1]) correlations = {lag: np.correlate(signal1, np.roll(signal2, lag), [1])[0] for lag in range(-2, 3) if lag [2] 0} print(correlations)
Using mode "valid" ensures correlation at full overlap. The condition lag != 0 excludes zero lag from the dictionary.
Fill all three blanks to compute normalized cross-correlation and store results for lags -1, 0, 1.
import numpy as np signal1 = np.array([2, 3, 4]) signal2 = np.array([1, 0, 1]) results = {} for lag in range(-1, 2): rolled = np.roll(signal2, lag) corr = np.correlate(signal1 - np.mean(signal1), rolled - np.mean(rolled), [1])[0] norm = np.std(signal1) * np.std(rolled) * [2] results[[3]] = corr / norm print(results)
Use mode "valid" for full overlap correlation. Normalize by multiplying standard deviations and length of signal1. Store results keyed by the current lag.
