# [Numpy-discussion] Tensor contraction

Alan Bromborsky abrombo@verizon....
Sat Jun 12 17:29:55 CDT 2010

Friedrich Romstedt wrote:
> 2010/6/12 Alan Bromborsky <abrombo@verizon.net>:
>
>> If I have a single numpy array, for example with 3 indices T_{ijk} and I
>> want to sum over two them in the sense of tensor contraction -
>>
>> T_{k} = \sum_{i=0}^{n-1} T_{iik}.  Is there an easy way to do this with
>> numpy?
>>
>
> Also you can give:
>
> T[I, I, :].sum(axis=0)
>
> a try with:
>
> I = numpy.arange(0, n)  .
>
> This has the benefit to not be limited to two-dimensional diagonals,
> like .diagonal() is.
>
>
> But note that for:
> T[:, I, I]
> the shape is reversed with respect to that of:
> T[I, :, I]  and T[I, I, :]  .
>
> I think it should be written in the docs how the shape is derived.
>
> hth,
> Friedrich
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
Your method works, but I should have posed the general case.  You have
an array T_{i_{1}...i_{r}} and you wish to calculate

T_{i_{1}...i_{r-2}} =
\sum_{i_{j}=i_{k}=0}^{n-1}T_{i_{1}...i_{j}...i_{k}...i_{r}}

I don't have a clue as to how to generalize your method.