1
$\begingroup$

I am trying to write a sum of the form $$\sum_{i<j}f_{ij}$$ 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?

$\endgroup$
4
  • 3
    $\begingroup$ Sum[f[[i,j]], {j,1,4},{i,1,j-1}]? $\endgroup$
    – Hausdorff
    Commented Mar 8, 2022 at 15:06
  • $\begingroup$ I thought about that too, but does mathematica know how to deal with the case j=1 ? $\endgroup$
    – Student
    Commented Mar 8, 2022 at 15:40
  • 1
    $\begingroup$ If you're worried about that, you could always use Sum[f[[i,j]], {j,2,4},{i,1,j-1}] instead. $\endgroup$ Commented Mar 8, 2022 at 16:00
  • $\begingroup$ @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. $\endgroup$
    – Hausdorff
    Commented Mar 8, 2022 at 16:11

4 Answers 4

1
$\begingroup$

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]

$\endgroup$
2
  • $\begingroup$ thanks again :) $\endgroup$
    – Student
    Commented Mar 8, 2022 at 15:40
  • $\begingroup$ you're welcome :-) $\endgroup$
    – user49048
    Commented Mar 8, 2022 at 15:40
1
$\begingroup$

Another way likes @kcr's method.

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

shorter.

$\endgroup$
1
$\begingroup$

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])
$\endgroup$
3
  • 1
    $\begingroup$ Plus @@ kind of equals to Total@ $\endgroup$ Commented Mar 8, 2022 at 16:05
  • 1
    $\begingroup$ Subsets[Range[4], {2}] // Map[Apply@f] // Total also works. $\endgroup$ Commented Mar 8, 2022 at 16:07
  • $\begingroup$ @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 :-) $\endgroup$
    – user49048
    Commented Mar 8, 2022 at 16:25
0
$\begingroup$

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]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.