Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3-D Matrix Multiplication in Numpy

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

like image 875
ѕняєє ѕιиgнι Avatar asked Nov 04 '18 09:11

ѕняєє ѕιиgнι


People also ask

How do you multiply a 3X3 matrix in Python?

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.

Can you multiply 3D matrices?

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.

How do you multiply 3X3 matrices?

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.


1 Answers

See Python Broadcasting

bob.reshape((2, 1, 4)) * tim.reshape((1, 7, 4))
like image 157
dobkind Avatar answered Sep 22 '22 23:09

dobkind