Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

broadcast each row of A along B, avoiding `repeat`

I have 2 2D arrays, with 1 axis of the same dimension:

a = np.array(np.arange(6).reshape((2,3)))
b = np.array(np.arange(12).reshape((3,4)))

I want to multiply and broadcast each row of a with b, that is

b_r = np.repeat(b[:,:,None], 2, axis=2)
ab = a.T[:,None,:] * b_r

Is it possible to do the broadcasting while avoiding the repeat? The idea is to avoid unnecessary memory allocation for the repeat operation.

like image 546
Itamar Katz Avatar asked Dec 29 '25 05:12

Itamar Katz


1 Answers

You can just feed in b[:,:,None] without the repeat, as broadcasting with its very definition would broadcast it for you.

Thus, simply do -

ab = a.T[:,None,:]*b[:,:,None]

We can make it a bit compact though by skipping the trailing : for a and using ... to replace :,: for b, like so -

ab = a.T[:,None]*b[...,None]

For the kicks, here's one using np.einsum, which would be little less performant, but more expressive once we get past its string notation -

ab = np.einsum('ij,jk->jki',a,b)
like image 127
Divakar Avatar answered Dec 30 '25 21:12

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!