Correlation of a 1D array from beginning to all points, a kind of sliding correlation

59 Views Asked by At

I have a 1D array and want to find the correlation of the series of first 2 elements, then first 3 elements... until all elements. I can do it with numpy in a loop; here is my code:

data = np.array([10,5,8,9,15,22,26,11,15,16,18,7,4,8,-2,-3,-4,-6,-2,0,10,0,5,8])
correl = np.zeros(data.shape)
for i in range(1, data.shape[0]):
     correl[i] = np.corrcoef(data[0: i+1], np.arange(i+1))[0, 1]
print(correl)

and the result is:

[ 0.    -1.    -0.397  0.     0.607  0.799  0.88   0.64   0.581  0.556
  0.574  0.322  0.078 -0.02  -0.237 -0.383 -0.489 -0.572 -0.614 -0.634
 -0.568 -0.59  -0.573 -0.533]

I wonder how I can make it in numpy without a loop, i.e. be smarter/more efficient Any idea please?

0

There are 0 best solutions below