2

I have an array of shape (3,2):

import numpy as np
arr = np.array([[0.,0.],[0.25,-0.125],[0.5,-0.125]])

I was trying to build a matrix (matrix) of dimensions (6,2), with the results of the outer product of the elements i,i of arr and arr.T. At the moment I am using a for loop such as:

size = np.shape(arr)
matrix = np.zeros((size[0]*size[1],size[1]))
for i in range(np.shape(arr)[0]):
    prod = np.outer(arr[i],arr[i].T)
    matrix[size[1]*i:size[1]+size[1]*i,:] = prod

Resulting:

matrix =array([[ 0.      ,  0.      ],
               [ 0.      ,  0.      ],
               [ 0.0625  , -0.03125 ],
               [-0.03125 ,  0.015625],
               [ 0.25    , -0.0625  ],
               [-0.0625  ,  0.015625]])

Is there any way to build this matrix without using a for loop (e.g. broadcasting)?

1 Answer 1

3

Extend arrays to 3D with None/np.newaxis keeping the first axis aligned, while letting the second axis getting pair-wise multiplied, perform multiplication leveraging broadcasting and reshape to 2D -

matrix = (arr[:,None,:]*arr[:,:,None]).reshape(-1,arr.shape[1])

We can also use np.einsum -

matrix = np.einsum('ij,ik->ijk',arr,arr).reshape(-1,arr.shape[1])

einsum string representation might be more intuitive as it lets us visualize three things :

  • Axes that are aligned (axis=0 here).

  • Axes that are getting summed up (none here).

  • Axes that are kept i.e. element-wise multiplied (axis=1 here).

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.