I have two ndarray like
n1 = np.array([1,2,3,4])
n2 = np.array([1,2,3,4])
While dot product of them can done easily with np.dot(n1, n2)
, which gives 30 as the right answer. What if I need the dot to be operated on two subarrays from n1 and n2, e.g.
np.dot(np.array([1,2]), np.array([1,2])) # first two elements from arrays
np.dot(np.array([3,4]), np.array([3,4])) # last two elements
Gives [5, 25]. I could do it by hand split array and for loop. But wondering if there is a more pythonic and numpy way to do this?
Here's one way:
reshaping splits the arrays in to the desired blocks:
now multiply all elements together - and sum on the right axis (sometimes I guess as to axis).
That sum of products can also be expressed with
einsum
- but don't worry if the syntax is too new: