I am expanding code designed to perform a function on 2 vectors so that it instead handles 2 arrays of vectors. I was using numpy.dot to take the product of two 3x3 matrices. Now I want to do this with an array of 3x3 matrices. I was not able to figure out how to do this with numpy.einsum but I think that is what I need, I'm just struggling to understand how it works.
Here is an example of what I want using a loop. Is there a way to do this without the loop?
>>> import numpy as np
>>> m = np.arange(27).reshape(3,3,3)
>>> print m
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
>>> m2 = np.zeros(m.shape)
>>> for i in length(m):
m2[i] = np.dot(m[i],m[i])
>>> print m2
array([[[ 15., 18., 21.],
[ 42., 54., 66.],
[ 69., 90., 111.]],
[[ 366., 396., 426.],
[ 474., 513., 552.],
[ 582., 630., 678.]],
[[ 1203., 1260., 1317.],
[ 1392., 1458., 1524.],
[ 1581., 1656., 1731.]]])
I found a numpy.einsum syntax in this post Python, numpy, einsum multiply a stack of matrices which does what I want. I am not clear on why that works and want to understand how to construct the indexing strings for future uses.
>>> print np.einsum('fij,fjk->fik', V, V)
[[[ 15 18 21]
[ 42 54 66]
[ 69 90 111]]
[[ 366 396 426]
[ 474 513 552]
[ 582 630 678]]
[[1203 1260 1317]
[1392 1458 1524]
[1581 1656 1731]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With