3Correlating an array row-wise with a vectorCorrelating an array row-wise with a vector

This should work to compute the correlation coefficient for each row with a specified y in a vectorized manner.

```
X = np.random.random([1000, 10])
y = np.random.random(10)
r = (len(y) * np.sum(X * y[None, :], axis=-1) - (np.sum(X, axis=-1) * np.sum(y))) / (np.sqrt((len(y) * np.sum(X**2, axis=-1) - np.sum(X, axis=-1) ** 2) * (len(y) * np.sum(y**2) - np.sum(y)**2)))
print(r[0], np.corrcoef(X[0], y))
0.4243951, 0.4243951
```

Source: link

The first way you might consider doing this is in a loop with the np.corrcoef function, which returns the linear correlation coefficient between two vectors:

If N is large, or if you need to perform this calculation many times (with an outer loop wrapped around it), this will be very slow. We can time it as follows: We can write a function using NumPy’s vectorized arithmetic to compute these values all at once rather than in a loop. For example, np.multiply(X,y) (also given by X*y) performs element-wise multiplication of the vector y over all rows of the matrix X. The function might look something like this: If we try timing it as before:Source: link

In Matlab this would be possible with the corr function corr(X,y).
For Python however this does not seem possible with the np.corrcoef function:

import numpy as np X = np.random.random([1000, 10]) y = np.random.random(10) np.corrcoef(X,y).shapeOf course this could be done via a list comprehension:

np.array([np.corrcoef(X[i, :], y)[0,1] for i in range(X.shape[0])])

Source: link