Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying Numpy 3D arrays by 1D arrays

I am trying to multiply a 3D array by a 1D array, such that each 2D array along the 3rd (depth: d) dimension is calculated like:

1D_array[d]*2D_array

And I end up with an array that looks like, say:

[[
[1,1]
[1,1]]
[
[2,2]
[2,2]]
[
[3,3]
[3,3]]]

Which would be the result of correctly multiplying np.ones((3,2,2)) with [1,2,3].

I've been trying for some time now and whatever I seem to do I can't end up with this result, just variations on the theme. How do I correctly go about doing this?

Thanks for any help.

like image 740
dscm Avatar asked Jan 25 '13 00:01

dscm


People also ask

Can you multiply 3D matrices?

A 3D matrix is nothing but a collection (or a stack) of many 2D matrices, just like how a 2D matrix is a collection/stack of many 1D vectors. So, matrix multiplication of 3D matrices involves multiple multiplications of 2D matrices, which eventually boils down to a dot product between their row/column vectors.

Can we multiply two NumPy arrays?

NumPy array can be multiplied by each other using matrix multiplication. These matrix multiplication methods include element-wise multiplication, the dot product, and the cross product.

What happens when you multiply two NumPy arrays?

Multiply two numpy arraysIt returns a numpy array of the same shape with values resulting from multiplying values in each array elementwise. Note that both the arrays need to have the same dimensions.


1 Answers

Let's assume b=np.ones((3,2,2)) and a=np.array([1,2,3]). I really do like the answer of @Alok which uses the simple a[:, None, None] * b which surely works with your problem. What I dislike with this formulation is that it's quite dimension specific. What I mean is that it can only be used with 3 dimensional arrays, which was not true in my problem, where b could be a 1D or a 3D array with the exact same length for axis 0. I hence found a way to accommodate it to my problem :

broad_a = np.broadcast_to(a, b.T.shape).T
result = broad_a * b
print(result)
[[
[1,1]
[1,1]]
[
[2,2]
[2,2]]
[
[3,3]
[3,3]]]

Giving also the intended result for your case.

like image 172
Pierre Olivier Downey Avatar answered Sep 20 '22 08:09

Pierre Olivier Downey