Home > Mobile >  Is there a method to preform matrix multiplication through a 4d array (row-wise) in python, without
Is there a method to preform matrix multiplication through a 4d array (row-wise) in python, without

Time:06-29

So I have setup a 4d numpy array, and I'm trying to preform matrix multiplication row-wise in the 4d array. I'm trying to not use a for loop and np.linalg.multi_dot for the sake of trying to keep the programme as fast as possible. This is what it looks like for my simple test (2x2 of matrices, but my actual problem will have an mxn of matrices).

k1=np.array([[1,2],[3,4]]) 
k2=np.array([[5,6],[7,8]])
k3=np.array([[9,10],[11,12]])
k4=np.array([[13,14],[15,16]])
k5=np.array([[k1,k2],[k3,k4]])

So in the case above, somehow get k1.k2 and k3.k4 within the k5 array (keeping in mind that I only have access to k5). If it helps, each matrix itself will be 2x2. Therefore I would like the output of my code to give me the following:

[[[19 22]
 [43 50]]

[[267 286]
 [323 346]]]

Thank you to anybody willing to waste their time on me and this silly little question!

CodePudding user response:

>>> k5 = np.array([[k1, k2], [k3, k4], [k1, k2]])
>>> k5[:, 0] @ k5[:, 1]
array([[[ 19,  22],
        [ 43,  50]],

       [[267, 286],
        [323, 346]],

       [[ 19,  22],
        [ 43,  50]]])

CodePudding user response:

One of the best methods to do such codes (e.g. enter image description here

  • Related