0

I need to multiply each row of an array A with all rows of an array B element-wise. For instance, let's say we have the following arrays:

A = np.array([[1,5],[3,6]])
B = np.array([[4,2],[8,2]])

I want to get the following array C:

C = np.array([[4,10],[8,10],[12,12],[24,12]])

I could do this by using for loop but I think there could be a better way to do it.

EDIT: I thought of repeating and tiling but my arrays are not that small. It could create some memory problem.

2
  • While Divakar correctly deduced what you wanted, you really should have shown us the looped code. Or a (2,2,2) version of C rather than the (4,2). There are various ways that rows of A can be combined with the rows of B (e.g. np.kron(A,B)). Commented Sep 7, 2018 at 16:06
  • I'm sorry. I upvoted it but I forgot to accept it. Thanks for the reminder. Commented Sep 13, 2018 at 21:16

1 Answer 1

5

Leverage broadcasting extending dims for A to 3D with None/np.newaxis, perform the elementwise multiplication and reshape back to 2D -

(A[:,None]*B).reshape(-1,B.shape[1])

which essentially would be -

(A[:,None,:]*B[None,:,:]).reshape(-1,B.shape[1])

Schematically put, it's :

A     :  M x 1 x N
B     :  1 x K x N
out   :  M x K x N

Final reshape to merge last two axes and give us (M x K*N) shaped 2D array.


We can also use einsum to perform the extension to 3D and elementwise multiplication in one function call -

np.einsum('ij,kj->ikj',A,B).reshape(-1,B.shape[1])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.