Say I have two arrays a
and b
,
a.shape = (5,2,3)
b.shape = (2,3)
then c = a * b
will give me an array c
of shape (5,2,3)
with c[i,j,k] = a[i,j,k]*b[j,k]
.
Now the situation is,
a.shape = (5,2,3)
b.shape = (2,3,8)
and I want c
to have a shape (5,2,3,8)
with c[i,j,k,l] = a[i,j,k]*b[j,k,l]
.
How to do this efficiently? My a
and b
are actually quite large.
This should work:
a[..., numpy.newaxis] * b[numpy.newaxis, ...]
Usage:
In : a = numpy.random.randn(5,2,3)
In : b = numpy.random.randn(2,3,8)
In : c = a[..., numpy.newaxis]*b[numpy.newaxis, ...]
In : c.shape
Out: (5, 2, 3, 8)
Ref: Array Broadcasting in numpy
Edit: Updated reference URL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With