# [Numpy-discussion] Is there a better way to write a stacked matrix multiplication

Daniele Nicolodi daniele at grinta.net
Thu Oct 26 14:11:37 EDT 2017

```Hello,

is there a better way to write the dot product between a stack of
matrices?  In my case I need to compute

y = A.T @ inv(B) @ A

with A a 3x1 matrix and B a 3x3 matrix, N times, with N in the few
hundred thousands range.  I thus "vectorize" the thing using stack of
matrices, so that A is a Nx3x1 matrix and B is Nx3x3 and I can write:

y = np.matmul(np.transpose(A, (0, 2, 1)), np.matmul(inv(B), A))

which I guess could be also written (in Python 3.6 and later):

y = np.transpose(A, (0, 2, 1)) @ inv(B) @ A

and I obtain a Nx1x1 y matrix which I can collapse to the vector I need
with np.squeeze().

However, the need for the second argument of np.transpose() seems odd to
me, because all other functions handle transparently the matrix stacking.

Am I missing something?  Is there a more natural matrix arrangement that
I could use to obtain the same results more naturally?

Cheers,
Daniele
```