3
$\begingroup$

I have following sum: $$ \sum_{\substack{n,j\\j<n}}^{3} x_nx_j$$. How can I give this $j<n$ condition in Sum?

$\endgroup$
3
  • $\begingroup$ Table[x[n] x[j], {n, 1, 3}, {j, n, 3}] // Flatten // Total $\endgroup$
    – cvgmt
    Nov 12, 2020 at 14:08
  • $\begingroup$ Sorry @cvgmt, j shall be lower n. This is the right: Table[x[n] x[j], {n, 1, 3}, {j, 1, n - 1}] // Flatten // Total $\endgroup$
    – Akku14
    Nov 12, 2020 at 14:30
  • $\begingroup$ @Akku14 Thanks you, you are right. $\endgroup$
    – cvgmt
    Nov 12, 2020 at 14:33

4 Answers 4

7
$\begingroup$

For more complex condition:

Sum[Boole[j<n] x[n] x[j] ,{n,1,3},{j,1,3}]

For this simple condition:

@cvgmt give it as comment.


Just for fun:

Subsets[Array[x, 3], {2}] // Map[Apply@Times] // Total
$\endgroup$
1
  • $\begingroup$ thank you. I have used Boole to provide equal or not equal condition in sum previously; I was confused about whether it can be useful in this case also, $\endgroup$ Nov 12, 2020 at 17:18
4
$\begingroup$

The most direct solution is simply:

Sum[x[n] x[j], {n, 1, 3}, {j, 1, n}]

(* x[1]^2 + x[1]*x[2] + x[2]^2 + x[1]*x[3] + x[2]*x[3] + x[3]^2 *)

The same sort of thing works with NSum, Product and Product.

$\endgroup$
1
  • $\begingroup$ I think you are almost right. Just the upper limit of j should be n-1. $\endgroup$ Nov 12, 2020 at 16:49
3
$\begingroup$
SparseArray[{n_, j_} /; j < n -> Subscript[x, n] Subscript[x, j], {3, 
    3}] // Flatten // Total
$\endgroup$
2
$\begingroup$

As usual, there are several ways to do it with Mathematica depending on the specific features that you want. Suppose you want to do some processing on all cases where $i<j$ where $i,j$ are in some range or list. The following code, in order of complexity, will each produce such a list of tuples:

r = Range[3];
Subsets[r, {2}]
Cases[Tuples[r, 2],  {i_,j_}/;i<j]
Select[Tuples[r, 2], #[[1]]<#[[2]]&]
Flatten[Table[If[i<j, {i,j}, Nothing], {i,r},{j,r}]

Once you have such a list L of {i,j} tuples, then you can find the sum of f[i,j] over all tuples with code such as:

Plus@@(L /. {i_,j_}->f[i,j])
Plus@@(# /. ij_->f@@ij& /@ L)

Same thing with the product using Times instead of Sum.

$\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.