Re: fastest way to do pair-sum / make pair-list

*To*: mathgroup at smc.vnet.net*Subject*: [mg23257] Re: [mg23170] fastest way to do pair-sum / make pair-list*From*: Hartmut Wolf <hwolf at debis.com>*Date*: Sat, 29 Apr 2000 22:05:01 -0400 (EDT)*Organization*: debis Systemhaus*References*: <200004210348.XAA19772@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

Wijnand Schepens schrieb: > > 1. > > What is the most efficient way to calculate the sum > > Sum f [ (x[[i]]-x[[j]])^2 ] > i<j > > ?? > > Example: > > I have a vector of real numbers: > lst = N[Range[100]]; > and a function operating on a number: > f[r2_]:=(r2-1.0)^2 > > Is > > Sum[ Sum[ f [ (lst[[i]]-lst[[j]])^2 ] , {j,i+1,Length[lst]}], > {i,1,Length[lst-1]}] > > the fastest way?? > > This kind of sum is very common in Molecular Modelling, where the total > energy of a system is often a sum of pair-energies, which only depend on > the distance between atoms. > I was surprised that I didn't find anything on sums over pairs in > Mathematica... > > 2. > > What is the most efficient way to generate a list of pairs starting from > a list?? > Is there a standard Mathematica routine which does this? > > e.g. {a,b,c,d} ----> {{a,b},{a,c},{a,d},{b,c},{b,d},{c,d}} > > or {x1,x2,...} -----> { {xi,xj} ...} > with i<j > > Best solution I found was > topairs[lst_] := > Module[{l=Length[lst]}, > Map[(Sequence @@ #1) &, > Table[ lst [[{i, j}]], {i, 1, l - 1}, {j, i + 1, l}] > ] > ] > > Another possibility would be > topairs2[lst_] := > Module[{l = Length[lst]}, > Partition[ > Flatten[ > Table[ lst[[{i, j}]], {i, 1, l - 1}, {j, i + 1, l}] > ], 2 > ] > ] > > but this doesn't have the same effect if operating on a list of lists > topairs[{{a1, a2}, {b1, b2}, {c1, c2}}] > gives what we want, > topairs2[{{a1, a2}, {b1, b2}, {c1, c2}}] > not Dear Wijnand, assume you have a list r of your atom distances, with length n, (n=4 in the example) then perhaps you would like to try out the following: Plus @@ Join @@ Array[ If[#1 < #2, f[(r[[#1]] - r[[#2]])^2], Unevaluated[Sequence[]]] &, {4, 4}] f[(r[[1]] - r[[2]])^2] + f[(r[[1]] - r[[3]])^2] + f[(r[[2]] - r[[3]])^2] + f[(r[[1]] - r[[4]])^2] + f[(r[[2]] - r[[4]])^2] + f[(r[[3]] - r[[4]])^2] (BTW are you shure about your arguments to f? I would have assumed f[(r[[i]] - r[[j]])] or else f[Sqrt[(r[[i]] - r[[j]]).(r[[i]] - r[[j]])]] ) Kind regards, Hartmut

**References**:**fastest way to do pair-sum / make pair-list***From:*Wijnand Schepens <Wijnand.Schepens@rug.ac.be>