2

Let's say I have the following NumPy arrays:

i = array([2, 4, 5])
j = array([0, 1, 2])

I would like to have a very efficient method (built-in if possible) to sum those vectors and have an output that looks like this:

[[2 4 5]
 [3 5 6]
 [4 6 7]]

So basically each column is the array j to which the k th element of i has been added (k = 0, 1, 2 in this case)

2 Answers 2

3

Use numpy.add.outer.

>>> import numpy as np                                                                                                 
>>> i = np.array([2, 4, 5])                                                                                            
>>> j = np.array([0, 1, 2])                                                                                            
>>>                                                                                                                    
>>> np.add.outer(j, i)                                                                                                 
array([[2, 4, 5],
       [3, 5, 6],
       [4, 6, 7]])
Sign up to request clarification or add additional context in comments.

Comments

3

Or with broadcasting:

In [272]: i[:,None]+j
Out[272]: 
array([[2, 3, 4],
       [4, 5, 6],
       [5, 6, 7]])

i[:,None] makes a (3,1) array, which broadcasts with a (3,) (or (1,3)) to make a (3,3).

1 Comment

Heads up, I was recently scolded for using None over np.newaxis. ;)

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.