Reputation: 365
I have an array of N vectors, each with a size of 3:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]]
It is needed to find a dot product of each of the vectors with itself.
Thus, the result will be a 3-dimensional array of shape (N,3,3). One approach is to use the following for loop:
for vector in np.arange(15).reshape(-1,3):
np.outer(vector, vector)
Since the array can be arbitrarily large, I need to find a vectorized solution.
Upvotes: 0
Views: 98
Reputation: 231385
You aren't summing over any axis, are you? Just a 'batched' outer?
In [115]: arr=np.arange(15).reshape(5,3)
In [116]: arr[:,:,None]*arr[:,None,:] #using broadcasting
Out[116]:
array([[[ 0, 0, 0],
[ 0, 1, 2],
[ 0, 2, 4]],
[[ 9, 12, 15],
[ 12, 16, 20],
[ 15, 20, 25]],
[[ 36, 42, 48],
[ 42, 49, 56],
[ 48, 56, 64]],
[[ 81, 90, 99],
[ 90, 100, 110],
[ 99, 110, 121]],
[[144, 156, 168],
[156, 169, 182],
[168, 182, 196]]])
In [117]: _.shape
Out[117]: (5, 3, 3)
arr[:,:,None]@arr[:,None,:]
does the same thing, summing on that size 1 'dummy' dimension.
Upvotes: 2