# How to sum over a two tensor with a simple constraint of the form $i<j$?

I am trying to write a sum of the form $$\sum_{i where $$i,j\in \{1,2,3,4\}.$$

I want to write something like Sum[f[[i,j]], {j,1,4},{i,1,j}] but then this is equal to the following sum $$\sum_{i\leq j}f_{ij}.$$

I know that I can subtract the $$f_{ii}$$ from this and recover the answer, but the quantities that I am summing over involve several metrics and tensors so I was wondering if there is a clean way to write sums like I mentioned earlier?

• Sum[f[[i,j]], {j,1,4},{i,1,j-1}]? Commented Mar 8, 2022 at 15:06
• I thought about that too, but does mathematica know how to deal with the case j=1 ? Commented Mar 8, 2022 at 15:40
• If you're worried about that, you could always use Sum[f[[i,j]], {j,2,4},{i,1,j-1}] instead. Commented Mar 8, 2022 at 16:00
• @ShreyAryan Yes. Mathematica follows the common convention that if the upper bound is smaller than the lower bound, then Sum returns 0. Table and Product behave similarly, returning {} and 1 respectively. Commented Mar 8, 2022 at 16:11

You can use the following:

Sum[Boole[i < j] f[i, j], {i, 1, 4}, {j, 1, 4}]


f[1, 2] + f[1, 3] + f[1, 4] + f[2, 3] + f[2, 4] + f[3, 4]

• thanks again :) Commented Mar 8, 2022 at 15:40
• you're welcome :-)
– user49048
Commented Mar 8, 2022 at 15:40

Another way likes @kcr's method.

f @@@ Subsets[Range[4], {2}] // Total


shorter.

This also works

Plus @@ (Subsets[Range[4], {2}] /. {i_, j_} -> f[i, j])


f[1, 2] + f[1, 3] + f[1, 4] + f[2, 3] + f[2, 4] + f[3, 4]

I missed the following, which is simpler and equivalent to the above. Thanks to the comment by @ AsukaMinato that pointed it out

Total @ (Subsets[Range[4], {2}] /. {i_, j_} -> f[i, j])

• Plus @@ kind of equals to Total@ Commented Mar 8, 2022 at 16:05
• Subsets[Range[4], {2}] // Map[Apply@f] // Total also works. Commented Mar 8, 2022 at 16:07
• @AsukaMinato yes, that's also a very nice way to go about it. Although, I do prefer the answer you provided which is much shorter :-)
– user49048
Commented Mar 8, 2022 at 16:25

Another one-liner -and again thanks to @AsukaMinato for the previous comment

Total[Normal@
SparseArray[{i_, j_} /; i < j :> f[i, j], {4, 4}], Infinity]