I wonder if there is a built-in operation which would free my code from Python-loops.
The problem is this: I have two matrices A
and B
. A
has N
rows and B
has N
columns. I would like to multiply every i
row from A
with corresponding i
column from B
(using NumPy broadcasting). The resulting matrix would form i
layer in the output. So my result would be 3-dimensional array.
Is such operation available in NumPy?
Yes, in it's simplest form you just add "zero" dimensions so the NumPy broadcasts along the rows of
A
and columns ofB
:The result has a shape of
(5, 3, 4)
and you can easily move the axis around if you want a different shape. For example usingnp.moveaxis
:With a shape of
(3, 4, 5)
.