Solution Code -
import numpy as np
Run example to demonstrate steps -
In [149]: import numpy as np In [150]: a = np.random.randint(0,9,(4,2,3)) In [151]: b = np.random.randint(0,9,(2,1)).ravel() In [152]: whos Variable Type Data/Info ------------------------------- a ndarray 4x2x3: 24 elems, type `int32`, 96 bytes b ndarray 2: 2 elems, type `int32`, 8 bytes In [153]: given_axis = 1
Now we want to perform stepwise multiplication along the given axis = 1 . Let create a dim_array :
In [154]: dim_array = np.ones((1,a.ndim),int).ravel() ...: dim_array[given_axis] = -1 ...: In [155]: dim_array Out[155]: array([ 1, -1, 1])
Finally, change form b and do elemental multiplication:
In [156]: b_reshaped = b.reshape(dim_array) ...: mult_out = a*b_reshaped ...:
Check the whos information again and pay particular attention to b_reshaped and mult_out :
In [157]: whos Variable Type Data/Info --------------------------------- a ndarray 4x2x3: 24 elems, type `int32`, 96 bytes b ndarray 2: 2 elems, type `int32`, 8 bytes b_reshaped ndarray 1x2x1: 2 elems, type `int32`, 8 bytes dim_array ndarray 3: 3 elems, type `int32`, 12 bytes given_axis int 1 mult_out ndarray 4x2x3: 24 elems, type `int32`, 96 bytes