0

Is it possible to apply numpy broadcasting (with 1D arrays),

x=np.arange(3)[:,np.newaxis]
y=np.arange(3)
x+y=
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

to 3d matricies similar to the one below, such that each element in a[i] is treated as a 1D vector like in the example above?

a=np.zeros((2,2,2))
a[0]=1
b=a
result=a+b

resulting in

result[0,0]=array([[2, 2],
                   [2, 2]])

result[0,1]=array([[1, 1],
                   [1, 1]])

result[1,0]=array([[1, 1],
                   [1, 1]])

result[1,1]=array([[0, 0],
                   [0, 0]])
Alex
  • 73
  • 1
  • 11
  • Could you use a random array and not that zeros array to demonstrate the expected output? – Divakar Sep 08 '17 at 18:51
  • I used the zeros array so that it would be easy to solve by hand, I had hoped that the above 1D array example would clarify what my intentions were. But hopefully the solution will clarify to other viewers what I wanted. – Alex Sep 08 '17 at 18:58

2 Answers2

3

You can do this in the same way as if they are 1d array, i.e, insert a new axis between axis 0 and axis 1 in either a or b:

a + b[:,None]    # or a[:,None] + b

(a + b[:,None])[0,0]
#array([[ 2.,  2.],
#       [ 2.,  2.]])

(a + b[:,None])[0,1]
#array([[ 1.,  1.],
#       [ 1.,  1.]])

(a + b[:,None])[1,0]
#array([[ 1.,  1.],
#       [ 1.,  1.]])

(a + b[:,None])[1,1]
#array([[ 0.,  0.],
#       [ 0.,  0.]])
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • 1
    its that simple, i think when trying this method, i didnt use the index to specify which array should appear, and instead made all the arrays appear ie a+b[:,none], and that confused me as it didnt look like the correct output. – Alex Sep 08 '17 at 18:54
  • I don't doubt. It's not easy to identify a 4 dimensional array visually. – Psidom Sep 08 '17 at 18:56
  • Sure, but `None` should not be used, and `np.newaxis` should be used in its place. – Reinderien Sep 08 '21 at 16:42
2

Since a and b are of same shape, say (2,2,2), a+b will indeed work. The way broadcasting works is that it matches the dimensions of the operands in reverse order, starting from the last dimension going up (e.g. considering columns before rows in a two-dimensional case). If the dimensions match then the next dimension is considered.

In case the dimensions don't match AND if one of the dimensions is 1 then that operand's dimension is repeated to match the other operand (e.g. if a.shape = (2,1,2) and b.shape = (2,2,2) then the values at the 1st dimension of a are repeated to make the shape (2,2,2))

L_W
  • 942
  • 11
  • 18
Rakesh K
  • 173
  • 1
  • 10