user1654183
user1654183

Reputation: 4605

Complicated numpy array multiplications

I have two arrays:

 a = [[a11,a12],
      [a21,a22]]

 b = [[b11,b12],
      [b21,b22]]

What I would like to do is build up a matrix as follows:

xx = np.mean(a[:,0]*b[:,0])
xy = np.mean(a[:,0]*b[:,1])
yx = np.mean(a[:,1]*b[:,0])
yy = np.mean(a[:,1]*b[:,1])

and return an array c such that

c = [[xx,xy],
      yx,yy]]

Is there a nice pythonic way to do this in numpy? Because at the moment I have done it by hand, exactly as above, so the dimensions of the output array are coded in by hand, rather than determined as according to the size of the input arrays a and b.

Upvotes: 1

Views: 70

Answers (1)

Jaime
Jaime

Reputation: 67507

Is there an error in your third element? If, as seems reasonable, you want yx = np.mean(a[:,1]*b[:,0]) instead of yx = np.mean(b[:,1]*a[:,0]), then you can try the following:

a = np.random.rand(2, 2)
b = np.random.rand(2, 2)
>>> c
array([[ 0.26951488,  0.19019219],
       [ 0.31008754,  0.1793523 ]])
>>> np.mean(a.T[:, None, :]*b.T, axis=-1)
array([[ 0.26951488,  0.19019219],
       [ 0.31008754,  0.1793523 ]])

It will actually be faster to avoid the intermediate array and express your result as a matrix multiplication:

>>> np.dot(a.T, b) / a.shape[0]
array([[ 0.26951488,  0.19019219],
       [ 0.31008754,  0.1793523 ]])

Upvotes: 3

Related Questions