Search code examples
pythonalgorithmmatrix-multiplication

Matrix splitting and multiplication in python


I have this 2 matrix: first [P,1] and second [N*P,2], in Python.

I want to multiplicate the first for the [P,2] submatrix of the second, N-times (without for cycles).

I'll give you an example:

a=[1,2,3]
b=[[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]

So, in this case, P=3 N=2. The result should be a matrix [N,2]. In the example:

res=[[22,28],[58,64]]

I've tried with reshape(P,N*2), but I don't it can be worth. Suggestions?


Solution

  • Depending on the orders you have, what you want is

    np.sum(a[None,:,None]*b.reshape(2,3,2), axis=1)
    

    You need to retranspose your data in an intermediate space because they are not interleaved as we expect.