Use None/newaxis
to added a new middle dimension (reshape
also does this):
In [36]: b.shape
Out[36]: (2, 4)
In [37]: a.shape
Out[37]: (2, 3, 4)
In [38]: b[:,None,:]*a
Out[38]:
array([[[ 1, 0, 3, 0],
[ 5, 0, 7, 0],
[ 9, 0, 11, 0]],
[[ 0, 0, 0, 16],
[ 0, 0, 0, 20],
[ 0, 0, 0, 24]]])
In [39]: b[:,None,:].shape
Out[39]: (2, 1, 4)
broadcast_to
can't add that extra dimension automatically. It follows the same rules as b*a
operations. It can add leading dimensions if needed, and scale size 1 dimensions. But for anything else, you have to be explicit.
In [41]: np.broadcast_to(b, (2,3,4))
Traceback (most recent call last):
File "<ipython-input-41-3c3268de7ce1>", line 1, in <module>
np.broadcast_to(b, (2,3,4))
File "<__array_function__ internals>", line 5, in broadcast_to
File "/usr/local/lib/python3.8/dist-packages/numpy/lib/stride_tricks.py", line 411, in broadcast_to
return _broadcast_to(array, shape, subok=subok, readonly=True)
File "/usr/local/lib/python3.8/dist-packages/numpy/lib/stride_tricks.py", line 348, in _broadcast_to
it = np.nditer(
ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (2,4) and requested shape (2,3,4)
In [42]: np.broadcast_to(b[:,None,:], (2,3,4))
Out[42]:
array([[[1, 0, 1, 0],
[1, 0, 1, 0],
[1, 0, 1, 0]],
[[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]]])