# a.shape = (3,4)# b.shape = (4,1). for i in range(3): for j in range(4): c[i][j] = a[i][j] + b[j]

How do you vectorize this?

Regards!

How do you vectorize this?

Regards!

If you first transpose b to be a 1 x 4 row vector, then youâ€™re just adding it to each row of a, right?

Note that numpy supports the concept of â€śbroadcastingâ€ť, which means that it can expand a vector by duplicating it so that you can do â€śelementwiseâ€ť operations with a matrix, if the dimensions of the two objects are compatible in that way. Try this and watch what happens:

```
np.random.seed(42)
A = np.random.rand(3,4)
print("A = " + str(A))
b = np.ones((3,1))
print("b = " + str(b))
C = A + b
print("C = " + str(C))
```

Running that gives this:

```
A = [[0.37454012 0.95071431 0.73199394 0.59865848]
[0.15601864 0.15599452 0.05808361 0.86617615]
[0.60111501 0.70807258 0.02058449 0.96990985]]
b = [[1.]
[1.]
[1.]]
C = [[1.37454012 1.95071431 1.73199394 1.59865848]
[1.15601864 1.15599452 1.05808361 1.86617615]
[1.60111501 1.70807258 1.02058449 1.96990985]]
```

1 Like