Efficient way to "broadcast" the sum of elements of two 1D arrays to a 2D array

Viewed 57

Is there a more efficient way (without loops) to do this with Numpy ?:

for i, x in enumerate(array1):
    for j, y in enumerate(array2):
        result[i, j] = x + y

I was trying to use einsum without success yet.

Thank you !

1 Answers

Simply use broadcasting with an extra dimension:

result = array1[:,None]+array2
Related