# [Numpy-discussion] array of matrices

Hans-Andreas Engel engelh@deshaw....
Tue Mar 31 20:40:54 CDT 2009

```Robert Kern <robert.kern <at> gmail.com> writes:
> On Sat, Mar 28, 2009 at 23:15, Anne Archibald <peridot.faceted <at> gmail.com>
wrote:
> > 2009/3/28 Geoffrey Irving <irving <at> naml.us>:
> >> On Sat, Mar 28, 2009 at 12:47 AM, Robert Kern <robert.kern <at> gmail.com>
wrote:
> >>> 2009/3/27 Charles R Harris <charlesr.harris <at> gmail.com>:
> >>>>
> >>>> On Fri, Mar 27, 2009 at 4:43 PM, Robert Kern <robert.kern <at> gmail.com>
wrote:
> >>>>>
> >>>>> On Fri, Mar 27, 2009 at 17:38, Bryan Cole <bryan <at> cole.uklinux.net>
wrote:
> >>>>> > I have a number of arrays of shape (N,4,4). I need to perform a
> >>>>> > vectorised matrix-multiplication between pairs of them I.e.
> >>>>> > matrix-multiplication rules for the last two dimensions, usual
> >>>>> > element-wise rule for the 1st dimension (of length N).
> >>>>> >
(...)
> >>
> >> It'd be great if this operation existed as a primitive.
(...)
> >
> > The infrastructure to support such generalized ufuncs has been added
> > to numpy, but as far as I know no functions yet make use of it.
>
> I don't think there is a way to do it in general with dot(). Some
> cases are ambiguous. I think you will need separate matrix-matrix,
> matrix-vector, and vector-vector gufuncs, to coin a term.

By the way, matrix multiplication is one of the testcases for the generalized
ufuncs in numpy 1.3 -- this makes playing around with it easy:

In [1]: N = 10; a = randn(N, 4, 4); b = randn(N, 4, 4)

In [2]: import numpy.core.umath_tests

In [3]: (numpy.core.umath_tests.matrix_multiply(a, b) == [dot(ai, bi) for (ai,
bi) in zip(a, b)]).all()
Out[3]: True

Best, Hansres

```