So I have two matrices, one is I×H and the other I×I, where H = M*I. I would like to take the dot product of the first M rows of the first matrix with the first row of the second, the next M rows with the next row of the second, etc.
Does anyone know an easy way to do this in NumPy? I'm trying to avoid a loop.
import numpy as np
# just some examples
i = 5
m = 3
h = m * i
first = np.arange(h * i).reshape(h, i) # note dimension H×i, not I×H
second = np.arange(i * i).reshape(i, i)
# Let's compute the dot product of
# every column of `first`
# with every column of `second` (i.e. every row of `second` transposed):
#
full_matrix_product = np.dot(first, second.transpose()) # no (explicit) loops,
# but does much more
# multiplications than
# we need in the end.
# Extract the specific dot products you want:
wanted_rows = np.arange(h)
wanted_columns = np.arange(m).repeat(i)
result = full_matrix_product[wanted_rows, wanted_columns].reshape(m, i)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.