Tohiko - 7 months ago 15

Python Question

I have an ndarray,

`A`

and I want to multiply this ndarray element wise by another 1D array

`b`

`A.shape[i] = len(b)`

`i`

I can do this using

`np.tile`

`A = np.random.rand(2,3,5,9)`

b = np.random.rand(5)

i = 2

b_shape = np.ones(len(A.shape), dtype=np.int)

b_shape[i] = len(b)

b_reps = list(A.shape)

b_reps[i] = 1

B = np.tile(b.reshape(b_shape), b_reps)

# Here B.shape = A.shape and

# B[i,j,:,k] = b for all i,j,k

This strikes me as ugly. Is there a better way to do this?

Answer

For this particular example, the following code would do the trick:

```
result = A*b[:, np.newaxis]
```

For any value of `i`

, try this:

```
A2, B = np.broadcast_arrays(A, b)
result = A2*B
```