1

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.

2
  • is this definitely what you want: yx = np.mean(b[:,1]*a[:,0]) ? Commented Jan 27, 2014 at 12:33
  • Thank you - I made a typo, correct. Commented Jan 27, 2014 at 18:02

1 Answer 1

3

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 ]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.