Re: Summing above diagonal in a tensor
- To: mathgroup at smc.vnet.net
- Subject: [mg112603] Re: Summing above diagonal in a tensor
- From: Ray Koopman <koopman at sfu.ca>
- Date: Thu, 23 Sep 2010 04:19:15 -0400 (EDT)
- References: <i79hv2$oin$1@smc.vnet.net>
On Sep 20, 11:05 pm, Alice Lesser <alice.les... at bwin.org> wrote: > Hi group, > > Summing the elements of a matrix which are above the diagonal is easy: > > m = Table[Subscript[a, x, y], {x, 1, 3}, {y, 1, 3}] > Total[UpperTriangularize[m, 1], 2] > > gives > a_1,2 + a_1,3 + a_2,3 > of course. > > If I instead have a 4-dim tensor > > t = Table[ Subscript[a, x, y, z, q], {x, 1, 3}, {y, 1, 3}, {z, 1, 3}, {q, 1, 3}] > > is there a nifty way to get the sum of the elements which are above > the diagonal in the outer matrix and above the diagonal in the submatrices? > In other words I'm looking for the sum > > a_1,2,1,2 + a_1,2,1,3 + a_1,2,2,3 + a_1,3,1,2 + a_1,3,1,3 + a_1,3,2,3+ a_2, 3,1,2 + a_2,3,1,3 + a_2,3,2,3 > > UpperTriangularize only seems to work on matrices, not tensors. > I could of course solve this with a few ugly for-loops, but it would be nice to know if there is a better way. > > Thanks, > Alice t = Array[a,{3,3,3,3}]; Tr @ Extract[t, Select[Tuples[{1,2,3},4], #[[1]] < #[[2]] && #[[3]] < #[[4]] & ] ] a[1,2,1,2] + a[1,2,1,3] + a[1,2,2,3] + a[1,3,1,2] + a[1,3,1,3] + a[1,3,2,3] + a[2,3,1,2] + a[2,3,1,3] + a[2,3,2,3]