Search code examples
pythonnumpymatrixaddition

Achieving add operation that maps shapes (a,d) + (b,d) to (a*b,d)


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?


Solution

  • Here you go, use repeat and tile:

    result = np.repeat(a,b.shape[0],axis=0) + np.tile(b,(a.shape[0],1))