Question

Is there an easy way to take the dot product of one element of an array with every other? So given:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

I would like to get the result:

array([  32.,   50.,  122.])

I.e. a[0] dot a[1], a[0] dot a[2], a[1] dot a[2].

The array I am working with will NOT be square; that's just an example.

Thanks!

Was it helpful?

Solution

>>> X = scipy.matrix('1 2 3; 4 5 6; 7 8 9')
>>> X*X.T
matrix([[ 14,  32,  50],
        [ 32,  77, 122],
        [ 50, 122, 194]])

It gives you more than what you wanted, but it's undeniably easy.

Or

>>> X = scipy.array([[1,2,3], [4,5,6], [7,8,9]])
>>> scipy.dot(X, X.T)
array([[ 14,  32,  50],
       [ 32,  77, 122],
       [ 50, 122, 194]])

OTHER TIPS

Since it looks like you are using numpy:

from itertools import combinations
import numpy as np

dot_products = [np.dot(*v) for v in combinations(vectors, 2)]

I checked this out and it appears to work on my python install.

Here's another one:

>>> a = numpy.array([[1, 2, 3],
...        [4, 5, 6],
...        [7, 8, 9]])
>>> numpy.array([numpy.dot(a[i], a[j]) for i in range(len(a)) for j in range(i + 1, len(a))])
array([ 32,  50, 122])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top