7

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.

ali_m
  • 71,714
  • 23
  • 223
  • 298
dscm
  • 123
  • 2
  • 5
  • 1
    If your arrays are `a` and `b`, are you looking for `b[:, None] * a`? – Alok Singhal Jan 25 '13 at 00:17
  • I just tried `b=np.ones((3,2,2))` `a=np.array(range(-1,2))` `ans=b[:, None]*a` But it threw an error: `ValueError: operands could not be broadcast together with shapes (1,3) (3,2,2)` I'm sure I'm just doing something foolish? – dscm Jan 25 '13 at 00:26
  • 9
    in this case I think you want `a[:, None, None] * b`. – Alok Singhal Jan 25 '13 at 00:28
  • Thankyou, that appears to be exactly what I want! – dscm Jan 25 '13 at 00:32
  • 1
    You ask for "2D arrays stacked along the 3rd dimension", but your example has them stacked along the 1st dimension. – Jaime Jan 25 '13 at 00:43
  • Good point Jaime, I made a mistake when I posed the question, so thankyou for the clarification. Hopefully other users that find this post will still be able to work with Alok's replies. – dscm Feb 06 '13 at 13:48
  • 2
    @Alok, you could post your comment as an answer since it solved the problem... – Saullo G. P. Castro May 09 '13 at 20:57

1 Answers1

2

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.