Re: Functional programming puzzle
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg1879] Re: Functional programming puzzle
- From: "Wm. Martin McClain" <wmm at chem.wayne.edu>
- Date: Sat, 12 Aug 1995 22:49:46 -0400
- Organization: Wayne State University, College of Science
Count Dracula <lk3a at kelvin.seas.virginia.edu> gave an elegant answer
my question:
> > I want a matrix of distances between the points in pts_List...
The Count's one-line solution depends upon an UNDOCUMENTED feature
of Outer, and also upon avoiding a named (Dracula's method,
Here it is:
Dracula's method:
>RijMat[pts_List]:=Sqrt[Map[#.#&,Outer[Subtract,pts,pts,1],{2}]]
The undocumented feature of Outer is its FOURTH PARAMETER, a level
specification. It would be interesting if the Count could divulge his
source of this information, apparently unavailable to mortals.
I created test lists of 5, 10, 20, 40, and 80 three-dimensional
Random points, with the following results (Dracula's method,
best observed times on a PowerMac 6100 with a speedup gadget):
{5 pts, 0.00 Sec},{10 pts,0.05 Sec},{20 pts,0.20 Sec},
{40 pts,0.80 Sec},{80 pts,3.20 Sec}}
Then I added the Outer level spec to my suggested method:
Rij[a_,b_]:=Sqrt[(a-b).(a-b)]
followed by
Outer[Rij,ptList,ptList,1]
My method, with its named external function Rij, took about twice as
long as Dracula's method.
Finally, I tried another method that uses
LinearAlgebra`MatrixManipulation`UpperDiagonalMatrix
to cut down on the number of multiplies. It took about the same
time as Rij method, but saved a little on space.
Question for WRI people: The matrix of distances is a vital
step in many stat mech calculations, and making it faster would
be a great service. Could you make a special kind "Outer", or perhaps
just an option for Outer, say Output->UpperTriangular, that would
avoid calculating the redundant lower triangle of results
(as well as the zeroes on the diagonal) ?