numpy add along an axis

3040 views python
-1

I would like to add two arrays with different dimensions by simply performing an identical addition all along one or more axes.

A non-vectorized solution:

x = np.array([[[1,2],[3,4],[5,6]],[[7,8],[9,0],[1,2]],[[3,4],[5,6],[7,8]],[[9,0],[1,2],[3,4]]]) #shape (4,3,2)
y = np.array([[1,2],[3,4],[5,6]]) #shape (3,2)

ans = np.empty(x.shape)
for i in range(x.shape[0]):
    ans[i] = x[i] + y

print(ans) #shape (4,3,2)

How can I make this broadcast appropriately?

answered question

1 Answer

5

Due to broadcasting [numpy-doc], you can simply use:

x + y

this gives:

>>> x + y
array([[[ 2,  4],
        [ 6,  8],
        [10, 12]],

       [[ 8, 10],
        [12,  4],
        [ 6,  8]],

       [[ 4,  6],
        [ 8, 10],
        [12, 14]],

       [[10,  2],
        [ 4,  6],
        [ 8, 10]]])
>>> (x + y).shape
(4, 3, 2)

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories