简体   繁体   中英

efficient way to compute numpy.ndarray internal multiplication

I have two matrices a and b with the same shape:

a = np.ndarray(shape=(3, 2), dtype=int)
b = np.ndarray(shape=(3, 2), dtype=int)

and i want the internal multiplication of them like:

    1 2
a = 4 5
    7 8

    9 8
b = 6 5
    3 2

and i want the result to be this 1x2 ndarray:

[1x9+4x6+7x3   2x8+5x5+8x2]

it is like we are computing the scalar dot product of the columns of the two matrix.

what i am doing now is:

np.diag(np.dot(np.transpose(a), b))

but it is not efficient and it is computing lots of other things that i don't need.

my matrices are much much bigger than these so it matters to find a more efficient solution.

You can do simple multiplication first and then sum over axis=0:

>>> a = np.array([[1, 2], [4, 5], [7, 8]])
>>> b = np.array([[9, 8], [6, 5], [3, 2]])
>>> (a * b).sum(axis=0)
array([54, 57])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM