I have a numpy array with shape (a,d)
and one with shape (b,d)
. I want to add all possible combinations of the first axis together, i.e. my final array should have shape (a*b,d)
. This can achieved using the following code:
import numpy as np
a = 2
b = 2
d = 3
matrix1 = np.random.rand(a,d)
matrix2 = np.random.rand(b,d)
result = np.zeros((a*b,d))
for i in range(a):
result[i*b:i*b+b] = matrix1[i,:] + matrix2
But I would like to do it without a for loop, and using numpy functions only. Is there an easy way to do this? Perhaps using np.einsum
or np.meshgrid
?