I have logged some data using 2 different devices on the same hardware, and the log interval was not the same. Now I have 2 arrays of different length(13518 and 68462 samples long), but the start and endpoints of these are the same, so I want to plot them as a function of each other to find any correlation. However, I can’t think of a way to change the length of an array, while keeping the general shape.
Lets say I have 2 arrays:
import numpy as np
import matplotlib.pyplot as plt
x = [1,3,5,7,9,4,2]
y = [3,8,16,5]
x1 = np.linspace(0,1,len(x))
x2 = np.linspace(0,1,len(y))
plt.figure()
plt.plot(x1,x)
plt.plot(x2,y)
plt.show()
The arrays clearly have correlation but can’t be plotted as function of each other because of the size difference.
>Solution :
Try scipy’s interp1d to create an interpolation function and shorter signal to match the length of the longer one
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
x = np.array([1, 3, 5, 7, 9, 4, 2])
y = np.array([3, 8, 16, 5])
t1 = np.linspace(0, 1, len(x))
t2 = np.linspace(0, 1, len(y))
f_interp = interp1d(t2, y, kind='linear')
y_interp = f_interp(t1)
plt.figure(figsize=(12, 4))
plt.subplot(121)
plt.plot(t1, x, 'b-', label='Signal x')
plt.plot(t2, y, 'r-', label='Signal y')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Original Signals')
plt.legend()
plt.grid(True)
plt.subplot(122)
plt.plot(x, y_interp, 'g.-')
plt.xlabel('Signal x')
plt.ylabel('Interpolated Signal y')
plt.title('Correlation Plot')
plt.grid(True)
plt.tight_layout()
plt.show()
correlation = np.corrcoef(x, y_interp)[0,1]
print(f"Correlation coefficient: {correlation:.3f}")
For your actual data
f_interp = interp1d(np.linspace(0, 1, 13518), shorter_signal, kind='linear')
interpolated_signal = f_interp(np.linspace(0, 1, 68462))
