Numpy: Sum two 1D arrays to get a 2D array

Viewed 584

Suppose I have two 1D arrays (a and b) and I want to sum them element-wise to create a 2D array (c). The 2D array has dimension (n,m) where n is the length of a and m is the length of b. The precise relation goes as: c[i][j] = a[i]+b[j], where i runs from 0 to n-1 and j runs from 0 to m-1. For example, consider the following code

a = np.asarray([1,2,3])
b = np.asarray([1,2])
c = a+b

This code gives me broadcasting error. The goal is to get c = [[2,3],[3,4],[4,5]]. Obviously we can use a loop to get every element of c, but I am looking for a way to do this without going through a loop.

2 Answers

For

(u + v).shape == (3, 2)

, we require:

u.shape == (3, 1)
v.shape == (1, 2)

Thus, the easiest way to accomplish this is by creating a new axis:

a = np.array([1, 2, 3])
b = np.array([1, 2])
c = a[..., np.newaxis] + b[np.newaxis, ...]

Another way could be to tile your arrays using the length of the other array. Note that I take the transpose of np.tile(b, (len(a), 1)) with .T.

import numpy as np

a = np.asarray([1,2,3])
b = np.asarray([1,2])
c = np.tile(a, (len(b), 1)) + np.tile(b, (len(a), 1)).T

hope it helps

Related