MathGroup Archive 2000

[Date Index] [Thread Index] [Author Index]

Search the Archive

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

  • To: mathgroup at smc.vnet.net
  • Subject: [mg23170] fastest way to do pair-sum / make pair-list
  • From: Wijnand Schepens <Wijnand.Schepens at rug.ac.be>
  • Date: Thu, 20 Apr 2000 23:48:42 -0400 (EDT)
  • Organization: RUG
  • Sender: owner-wri-mathgroup at wolfram.com

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



  • Prev by Date: output from a package
  • Next by Date: minimization of a function operating on a vector or reals
  • Previous by thread: RE: output from a package
  • Next by thread: Re: fastest way to do pair-sum / make pair-list