# numpy add along an axis

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?

Willem Van Onsem
answered question

### 1 Answer

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)
```

Willem Van Onsem
posted this

## Have an answer?

JD