Luis Michael Luethi
Luis Michael Luethi

Reputation: 69

Numpy: Dotproduct of all vectors in a list

Say I have a list of 800 vectors and every vector consists of 1440 scalars.

List = [(1, 2, 3, ... , 1440),
        (1, 2, 3, ... , 1440),
        (1, 2, 3, ... , 1440),
        ...]

How can I calculate the dot product of every vector to each other vector in the fastest way with python and numpy?

Upvotes: 2

Views: 597

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114440

You can use np.triu_indices or np.tril_indices to avoid computing the second half of the matrix. This won't affect the complexity of the computation, but may save some time for a sufficient number of long vectors:

a = np.array(x)
n = a.shape[0]
r, c = np.triu_indices(n)
result = np.empty((n, n))
result[r, c] = result[c, r] = np.sum(a[r] * a[c], axis=1)

Upvotes: 0

Pierre D
Pierre D

Reputation: 26251

If you want the symmetric matrix where x_ij is the dot product of a_i with a_j, then:

a = np.array(List)
x = a @ a.T

Upvotes: 1

Related Questions