Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiplication of 3-dimensional matrix in numpy

I think I asked the wrong question yesterday. What I actually want is to mutiply two 2x2xN matrices A and B, so that

C[:,:,i] = dot(A[:,:,i], B[:,:,i])

For example, if I have a matrix

A = np.arange(12).reshape(2, 2, 3)

How can I get C = A x A with the definition described above? Is there a built-in function to do this?


Also, if I multiply A (shape 2x2xN) with B (shape 2x2x1, instead of N), I want to get

C[:,:,i] = dot(A[:,:,i], B[:,:,1])
like image 210
LWZ Avatar asked Mar 20 '13 22:03

LWZ


1 Answers

Try using numpy.einsum, it has a little bit of a learning curve but it should give you what you want. Here is an example to get you started.

import numpy as np

A = np.random.random((2, 2, 3))
B = np.random.random((2, 2, 3))

C1 = np.empty((2, 2, 3))
for i in range(3):
    C1[:, :, i] = np.dot(A[:, :, i], B[:, :, i])

C2 = np.einsum('ijn,jkn->ikn', A, B)
np.allclose(C1, C2)
like image 197
Bi Rico Avatar answered Nov 05 '22 06:11

Bi Rico