Search code examples
pythonnumpymatrixmultiplication

Matrix special multiplication in numpy


I have two array m1 and m2 and I want to make a special multiplication : 1*8 + 2*6, 3*8 + 4*6, 1*2 + 2*6, 3*2 + 4*6, ... So I want this output. result = [20, 48, 14,30,..]

m1 = np.array([1,2,3,4])
m2 = np.array([8,6,2,6,2,5])

I'm sorry but I don't really know how to do that. I think with a for loop like this:

for x in m1:

Thank you


Solution

  • So obviously, your scalar products must be done 2 by 2, so you need to start reshaping your data:

    m1 = np.array([1,2,3,4]).reshape(2,2)
    m2 = np.array([8,6,2,6,2,5]).reshape(3,2)
    

    So now, you want the dot product of on the last column, and flatten the result, so do:

    np.dot(m2, m1.T).reshape(-1)