numpy-ndarraymultiplication

Multiplying numpy arrays across different axis


Let's say I have two arrays:

a = [
     [[-1, 0, 1], 
      [-2, 0, 2],
      [-3, 0, 3]],

     [[-4, 0, 4],
      [-5, 0, 5],
      [-6, 0, 6]]
    ] 

and

b = [
     [1, 3, 5],
     [7, 11, 13]
    ]

I'm trying to find the most elegant way to end up with the output

c = [
     [[-1, 0, 1], 
      [-6, 0, 6],
      [-15, 0, 15]],

     [[-28, 0, 28],
      [-55, 0, 55],
      [-78, 0, 78]]
    ] 

Is there some sort of function in numpy that can handle this elegantly?

I've browsed the documentation for np.multiply() and np.dot() and I haven't found a nice way to do it with those functions. I've suppose I could make some sort of ugly for loop to do it in, but I'm hoping for something more elegant.


Solution

  • you can do it using broadcasting

    firstly you need to check for the shapes of the array if they are not the same so you can board casting

    c= a[:, :, None] * b[None, :, :]
    
    print(c)