Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to multiply a matrix with every row in another matrix using numpy

Tags:

python

numpy

import numpy
A = numpy.array([
  [0,1,1],
  [2,2,0],
  [3,0,3]
])

B = numpy.array([
  [1,1,1],
  [2,2,2],
  [3,2,9],
  [4,4,4],
  [5,9,5]
])

Dimension of A: N * N(3*3)

Dimension of B: K * N(5*3)

Expected result is: C = [ A * B[0], A * B[1], A * B[2], A * B[3], A * B[4]] (Dimension of C is also 5*3)

I am new to numpy and not sure how to perform this operation without using for loops.

Thanks!

like image 884
Phoebe Avatar asked Jan 19 '26 02:01

Phoebe


1 Answers

By the math you provide, I think you are evaluating A times B transpose. If you want the resultant matrix to have the size 5*3, you can transpose it (equivalent to numpy.matmul(B.transpose(),A)).

import numpy
A = numpy.array([
  [0,1,1],
  [2,2,0],
  [3,0,3]
])

B = numpy.array([
  [1,1,1],
  [2,2,2],
  [3,2,9],
  [4,4,4],
  [5,9,5]
])

print(numpy.matmul(A,B.transpose()))
output :array([[ 2,  4, 11,  8, 14],
               [ 4,  8, 10, 16, 28],
               [ 6, 12, 36, 24, 30]])

for i in range(5):
    print (numpy.matmul(A,B[i]))
Output:
[2 4 6]
[ 4  8 12]
[11 10 36]
[ 8 16 24]
[14 28 30]
like image 65
Mayan Avatar answered Jan 20 '26 16:01

Mayan