Re: Summing above diagonal in a tensor
- To: mathgroup at smc.vnet.net
- Subject: [mg112601] Re: Summing above diagonal in a tensor
- From: Leonid Shifrin <lshifr at gmail.com>
- Date: Wed, 22 Sep 2010 01:58:01 -0400 (EDT)
Hi Alice, Here is a test tensor: In[111]:== Clear[a,tensor] (tensor == Array[a,{3,3,3,3}])//Short[#,5]& Out[112]//Short== {{{{a[1,1,1,1],a[1,1,1,2],a[1,1,1,3]},{a[1,1,2,1],a[1,1,2,2],a[1,1,2,3]},{a[1,1,3,1],a[1,1,3,2],a[1,1,3,3]}},{{a[1,2,1,1],a[1,2,1,2],a[1,2,1,3]},{a[1,2,2,1],a[1,2,2,2],a[1,2,2,3]},{a[1,2,3,1],a[1,2,3,2],a[1,2,3,3]}},{{a[1,3,1,1],a[1,3,1,2],a[1,3,1,3]},{a[1,3,2,1],a[1,3,2,2],a[1,3,2,3]},{a[1,3,3,1],a[1,3,3,2],a[1,3,3,3]}}},{{{a[2,1,1,1],a[2,1,1,2],a[2,1,1,3]},{<<1>>},{<<1>>}},{<<1>>},{<<1>>}},{<<1>>}} Here are a couple of brute force solutions: In[113]:== Total@Extract[tensor, Select[Tuples[Range/@Dimensions[tensor]],#[[1]]<#[[2]]&&#[[3]]<#[[4]]&]] Out[113]== 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] In[114]:== Total@Flatten@ MapIndexed[#1*Boole[#2[[1]] < #2[[2]] && #2[[3]] < #2[[4]]] &, tensor, {4}] Out[114]== 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] The following one I consider somewhat more elegant, since it does not go to the low-level position details and explicitly shows your request to "double - UpperTriangularize": In[115]:== Clear[fourthRankTensorUpperTriangularSum]; fourthRankTensorUpperTriangularSum[tensor_,n_]:== Module[{b,outerMatrix,rules}, outerMatrix== Array[b,Take[Dimensions[tensor],2]]; rules ==Flatten[ Thread/@Thread[outerMatrix->Map[UpperTriangularize[#,n]&,tensor,{2}]]]; Total[Flatten[UpperTriangularize[outerMatrix,n]/.rules]]]; In[117]:== fourthRankTensorUpperTriangularSum[tensor,1] Out[117]== 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] Hope this helps. Regards, Leonid On Tue, Sep 21, 2010 at 10:05 AM, Alice Lesser <alice.lesser 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 > > >