Sunday 18 August 2013

Create array of outer products in numpy

Create array of outer products in numpy

I have an array of n vectors of length m. For example, with n = 3, m = 2:
x = array([[1, 2], [3, 4], [5,6]])
I want to take the outer product of each vector with itself, then
concatenate them into an array of square matrices of shape (n, m, m). So
for the x above I would get
array([[[ 1, 2],
[ 2, 4]],
[[ 9, 12],
[12, 16]],
[[25, 30],
[30, 36]]])
I can do this with a for loop like so
np.concatenate([np.outer(v, v) for v in x]).reshape(3, 2, 2)
Is there a numpy expression that does this without the Python for loop?
Bonus question: since the outer products are symmetric, I don't need to m
x m multiplication operations to calculate them. Can I get this symmetry
optimization from numpy?

No comments:

Post a Comment