Python 3D-1D Array multiplication

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Python 3D-1D Array multiplication on this date .

Alright, so i want to multiply a 3D array and 1D array together and then do summation like in the example below

A = [Array([[[100, 100, 100],
            [100, 100, 100]],

            [[100, 100, 100],
            [100, 100, 100]]]), 

    Array([[[200, 200, 200],
            [200, 200, 200]],

            [[200, 200, 200],
            [200, 200, 200]]])]

Weight = [0.25,0.75]


# A[0]*Weight[0]+A[1]*Weight[1]

C = [[[100*0.25 + 200*0.75, 100*0.25 + 200*0.75, 100*0.25 + 200*0.75],
      [100*0.25 + 200*0.75, 100*0.25 + 200*0.75, 100*0.25 + 200*0.75]],
    
     [[100*0.25 + 200*0.75, 100*0.25 + 200*0.75, 100*0.25 + 200*0.75],
      [100*0.25 + 200*0.75, 100*0.25 + 200*0.75, 100*0.25 + 200*0.75]]]
    
  = [[[175, 175, 175],
      [175, 175, 175]],
    
     [[175, 175, 175],
      [175, 175, 175]]]

The question is how do i do it in python? I tried to use np.multiply, np.dot, np.matmul but none of them seems to work as i intended. Maybe i didn’t do it correctly. By the way, i also want it to be able to multiply even larger array, for example A Array with multiple Array() inside, not just 2 like in the example. And of course the length of Weight Array will follow the length of A Array. Also if possible i also wanna avoid using for-loop and use only numpy functions instead.

Answer

Simply broadcast the values and sum them up.

import numpy as np

A = np.array([np.array([[[100, 100, 100],
            [100, 100, 100]],

            [[100, 100, 100],
            [100, 100, 100]]]), 

    np.array([[[200, 200, 200],
            [200, 200, 200]],

            [[200, 200, 200],
            [200, 200, 200]]])])


Weight = np.array([0.25,0.75])

P = (A * Weight[:, None, None, None]).sum(0)

Or you can also use einsum. Replace the last line with –

P = np.einsum("ijkl,i->jkl", A, Weight)

Gives the same result.