I have two numpy arrays, x
of shape (m, 2)
and y
of shape (n, 2)
. I would like compute the (m, n, 2)
array where at position (i, j)
one finds the sum of x[i]
and y[j]
at out[i, j]
. List comprehension works
import numpy
x = numpy.random.rand(13, 2)
y = numpy.random.rand(5, 2)
xy = numpy.array([
[xx + yy for yy in y]
for xx in x
])
but I was wondering if there is a more efficient solution via numpy.add.outer
or something along those lines.
You can use numpys broadcasting rules to cast the first array to the shape (13, 1, 2)
and the second to the shape (1, 5, 2)
:
numpy.all(x[:, None, :] + y[None, :, :] == xy)
# True
The array is repeated across the dimension where None
is added (since it has length 1).
Therefore the shape of the output becomes (13, 5, 2)
.
xy = x[:, None]+y
应该做的伎俩。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.