1

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?

Thomas Wagenaar
  • 6,489
  • 5
  • 30
  • 73
  • Does this answer your question? [Cartesian product of x and y array points into single array of 2D points](https://stackoverflow.com/questions/11144513/cartesian-product-of-x-and-y-array-points-into-single-array-of-2d-points) – Nathan Furnal Oct 01 '21 at 11:52

1 Answers1

1

Here you go, use repeat and tile:

result = np.repeat(a,b.shape[0],axis=0) + np.tile(b,(a.shape[0],1))
kubatucka
  • 555
  • 5
  • 15