Reputation: 47
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)
Upvotes: 2
Views: 70
Reputation: 231738
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)
.
Upvotes: 3
Reputation: 78800
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]])
Upvotes: 3