Christoph
Christoph

Reputation: 1620

Dot product of every element with every other element of an array

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!

Upvotes: 2

Views: 3482

Answers (3)

thkala
thkala

Reputation: 86413

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])

Upvotes: 0

Steve Tjoa
Steve Tjoa

Reputation: 61114

>>> 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]])

Upvotes: 5

troutinator
troutinator

Reputation: 1198

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.

Upvotes: 1

Related Questions