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

Peter Creasey p.e.creasey.00 at googlemail.com
Thu Oct 26 17:01:53 EDT 2017


> > On Thu, Oct 26, 2017 at 12:11 PM, Daniele Nicolodi <daniele at grinta.net>
> > wrote:
> >
> >> 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))
> >>


If you only ever multiply your matrix inverse by a single vector then
you may also wish to consider

np.linalg.solve(B,A)

which usually has a better prefactor (although for 3x3 it's pretty
marginal, your hardware may vary).

Peter


More information about the NumPy-Discussion mailing list