What is the most elegant way to compute "inner" dot products of a multidimensional numpy array?
Let's assume I have 2 arrays a and b both of shape (2, 2, 2) (could be (n, n, 2) with n>= 2) and I want to compute the inner_dot(a, b) with the following definition:
np.array([[np.dot(a[0, 0, :], b[0, 0, :]), np.dot(a[1, 0, :], b[1, 0, :])],
[np.dot(a[0, 1, :], b[0, 1, :]), np.dot(a[1, 1, :], b[1, 1, :])]])
Here is an example:
a = np.arange(8).reshape(2, 2, 2)
b = np.arange(8).reshape(2, 2, 2)
Expected result:
array([[ 1, 41],
[13, 85]])
You can directly multiply both arrays and sum along the last axis. Also since you want the top right corner of the output as np.dot(a[1, 0, :], b[1, 0, :]), rather than 0,1 and presumably in the same fashion for the off-diagonal elements, you can transpose the result to get as expected:
(a*b).sum(-1).T
array([[ 1, 41],
[13, 85]])
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