3

I have two numpy.array objects x and y where x.shape is (P, K) and y.shape is (T, K). I want to do an outer sum on these two objects such that the result has shape (P, T, K). I'm aware of the np.add.outer and the np.einsum functions but I couldn't get them to do what I wanted.

The following gives the intended result.

  x_plus_y = np.zeros((P, T, K))
  for k in range(K):
    x_plus_y[:, :, k] = np.add.outer(x[:, k], y[:, k])

But I've got to imagine there's a faster way!

1 Answer 1

5

One option is to add a new dimension to x and add using numpy broadcasting:

out = x[:, None] + y

or as @FirefoxMetzger pointed out, it's more readable to be explicit with the dimensions:

out = x[:, None, :] + y[None, :, :]

Test:

P, K, T = np.random.randint(10,30, size=3)
x = np.random.rand(P, K)
y = np.random.rand(T, K)
x_plus_y = np.zeros((P, T, K))
for k in range(K):
    x_plus_y[:, :, k] = np.add.outer(x[:, k], y[:, k])

assert (x_plus_y == x[:, None] + y).all()
Sign up to request clarification or add additional context in comments.

1 Comment

I think this solution becomes more readable if we are explicit with the dimensions and write x[:, None, :] and y[None, :, :]. (x[:, None, :] + y[None, :, :])

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.