I have to multiply two 2-D matrices, bob
and tim
, in Numpy Python 3.x
bob.shape
gives (2,4)
tim.shape
gives (7,4)
This piece of code gives a 3-D matrix with a shape of (2,7,4)
np.array([foo*tim for foo in bob])
It gives the output I want. But, I was wondering if there was a more elegant/faster way to do this in numpy rather than me having to iterate through bob
Multiplication can be done using nested loops. Following program has two matrices x and y each with 3 rows and 3 columns. The resultant z matrix will also have 3X3 structure. Element of each row of first matrix is multiplied by corresponding element in column of second matrix.
A 3D matrix is nothing but a collection (or a stack) of many 2D matrices, just like how a 2D matrix is a collection/stack of many 1D vectors. So, matrix multiplication of 3D matrices involves multiple multiplications of 2D matrices, which eventually boils down to a dot product between their row/column vectors.
A 3×3 matrix has three rows and three columns. In matrix multiplication, each of the three rows of first matrix is multiplied by the columns of second matrix and then we add all the pairs.
See Python Broadcasting
bob.reshape((2, 1, 4)) * tim.reshape((1, 7, 4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With