How to improve matrix element manipulation in this scenario?

Viewed 23

Here is the problem and after I give a snippet. Consider that I have a X matrix n x d composed of n vectors of d dimensions.

    [ x1 ]   [ x1(1), ... , x1(d) ] 
X = [ .. ] = [ .....              ]
    [ xn ]   [ xn(1), ... , xn(d) ]

and another matrix A n x N composed of coefficients

    [ a11, ...,  a1N ]
A = [  ....
    [ an1, ..., anN ]

I would like to get the following matrix W n x (Nd) such that

   [ a11 x1, a12 x1, ..., a1N x1 ]
W =[ ...                         ]
   [ an1 xn, an2 xn, ..., anN xn ]

Now here is my snippet :

    n=2
    d=3
    N=4
    X = np.array([[5, 6, 0], [2, 6, 7]])
    A = np.array([[2, 3, 1, 1], [3, 2, 2, 2]])
    W = np.zeros(shape=(n,N*d))
    for i in range(0,n):
      bigX = np.tile(X[i],reps=N)
      bigA = np.repeat(A[i],repeats=d)
      W[i] = bigX * bigA
   print("W= ",W)

which leads to

W= [[10. 12.  0. 15. 18.  0.  5.  6.  0.  5.  6.  0.]
     [ 6. 18. 21.  4. 12. 14.  4. 12. 14.  4. 12. 14.]]

You can imagine that n,d,N can be much larger than the values in this snippet, and so I wander how to make this code much more efficient. I am pretty sure that there is some broadcasting method but I cannot figure out how to proceed. An idea?

1 Answers

Well, I think I have found that the problem is may be solved using simply

W = np.tile(X,reps=N) * np.repeat(A,repeats=d, axis=1)

but may be there a even simpler & more efficient solution.

Related