Laureano Ortellado
Laureano Ortellado

Reputation: 25

Matrix multiplication of a ndarray

I have a matrix, for instance, A = np.array([[1,0],[0,1]]) and ndarray of the form B = np.array([[1,2],[3,4],[5,6]]). I want a matrix multiplication of each array of the array B by the matrix A.

I did a for cycle, like this

C = []
for b in B:
    C.append(np.matmul(A,b))
C=np.array(C)

out[]:

array([[1, 2],
   [3, 4],
   [5, 6]])

But I know that this for cycle is time consuming. Is there a better way to do it?

Upvotes: 1

Views: 97

Answers (2)

hpaulj
hpaulj

Reputation: 231665

When you do funny things with matrix multiplication dimensions, einsum can help clarify what's going on.

In [40]: np.einsum('ij,kj->ki',A,B)
Out[40]: 
array([[1, 2],
       [3, 4],
       [5, 6]])

Here we are doing the sum-of-products on the j dimension, and putting B's first dimension first in the result. Ordinary matmul would be ij,jk->ik. From that we can see the need for the two transposes in the other answer.

([email protected]).T

Upvotes: 4

Lukas S
Lukas S

Reputation: 3603

Two things: First of all you can use normal matrix multiplication and transposing for that. And 2ndly you can use @ to ask for a matrix multiplication in python.

So try

([email protected]).T

or equivalently

([email protected])

Upvotes: 1

Related Questions