1

How do I find a matrix of all sums of two arrays?

With the input

x1 = np.array([0, 1])
x2 = np.array([1,2,3])

I want the output of this to be like this:

[[1, 2, 3], [2, 3, 4]]
2
  • 2
    Try : x1[:,None]+x2. Commented Jun 3, 2017 at 8:08
  • @Divakar thanks, that worked. Commented Jun 3, 2017 at 8:13

2 Answers 2

1

You can use NumPy's newaxis attribute:

x1[:, np.newaxis] + x2

which is an acronym for None:

In [2]: np.newaxis is None
Out[2]: True

Thus:

x1[:, None] + x2

also works.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use list comprehension like this example:

x1 = np.array([0, 1])
x2 = np.array([1,2,3])

final = [[j+k for j in x2] for k in x1]

# Or, maybe:
# final = np.array([[j+k for j in x2] for k in x1])
# >>> array([[1, 2, 3], [2, 3, 4]])

print(final)

Output:

[[1, 2, 3], [2, 3, 4]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.