# [Numpy-discussion] dot operations on multidimensional arrays

Charles R Harris charlesr.harris at gmail.com
Tue Dec 5 12:02:17 CST 2006

On 11/23/06, Carsten Rostgaard <Carsten.Rostgaard at fysik.dtu.dk> wrote:
>
> Hi!
> I am trying to use the "dot" method on multi-(more than 2)-dimensional
> arrays.
>
> Specifically I do
>     >> y = dot(a, b)
> where a is a 2D array and b is a 3D array.
>
> using numpy I get the the help:
> "
> dot(...)
>     dot(a,v) returns matrix-multiplication between a and b.
>     The product-sum is over the last dimension of a and the
>     second-to-last dimension of b.
> "
> I then expect that
>     >> y[i, j, k] = sum(a[i, :] * b[j, :, k])
> which is actually what I get.
>
> The question is then:
> 1) Is there any way to change the axis for which the product-sum is
> performed. This can of course be done by a swapaxis before and after the
> operation, but this makes the array non-contiguous, in which case the
> dot operation often makes bugs (at least in Numeric).
> 2) For complicated reasons we still use Numeric in our software package,
> and in this, "dot" behaves very strangely.
> According to the Numeric help:

In Numpy

tensordot(a, b, axes=2)
tensordot returns the product for any (ndim >= 1) arrays.

r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where

the axes to be summed over are given by the axes argument.
the first element of the sequence determines the axis or axes
in arr1 to sum over, and the second element in axes argument sequence
determines the axis or axes in arr2 to sum over.

When there is more than one axis to sum over, the corresponding
arguments to axes should be sequences of the same length with the first
axis to sum over given first in both sequences, the second axis second,
and so forth.

If the axes argument is an integer, N, then the last N dimensions of a
and first N dimensions of b are summed over.