I want to evaluate a sum like $\sum\limits_{j > i}^n q_i^k\, q_j^k$, where $n$ is the length of the vector $q^k$. The vector $q^k$ is, for example, $[q_1, q_2, q_3, q_4]$ and $i$ and $j$ correspond to the index of the vector elements.
This was my attempt; I got errors :/
Answer
vec = Table[q[i], {i, 4}]
(* {q[1], q[2], q[3], q[4]} *)
With[{l = Length[vec]},
Sum[vec[[i]] vec[[j]], {i, 1, l}, {j, i + 1, l}]
]
(* q[1] q[2] + q[1] q[3] + q[2] q[3] + q[1] q[4] + q[2] q[4] + q[3] q[4] *)
Plus @@ Times @@@ Subsets[vec, {2}]
(* q[1] q[2] + q[1] q[3] + q[2] q[3] + q[1] q[4] + q[2] q[4] + q[3] q[4] *)
Update
For binary vectors (see OP's comment), a fast approach would be:
vec = RandomInteger[{0, 1}, 10^6];
Binomial[Total[vec], 2] // RepeatedTiming
(* {0.0010, 124964252556} *)
(* comparison of the result with Jim Baldwin's answer *)
%[[2]] === (Total[vec^k]^2 - Total[vec^(2 k)])/2
(* True *)
Comments
Post a Comment