Re: Functional programming puzzle
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg1827] Re: Functional programming puzzle
- From: Scott.A.Hill at williams.edu (Lancelot)
- Date: Thu, 3 Aug 1995 23:52:49 -0400
- Organization: Williams College, Williamstown MA
In article <DCGM0w.5GH at wri.com>, Wm. Martin McClain <wmm at chem.wayne.edu> wrote:
>Let ptList = {{1,1,2},{2,1,3},{1,3,2}};
>
>I want a matrix of distances between the points in ptList.
>Any human would think you could get it with
>
>Rij[a_,b_]:=Sqrt[(a-b).(a-b)]
>
>followed by
>
>Outer[Rij,ptList,ptList]
[snip]
>I can do it for a short ptList this way:
>
>toNbrs = Thread[{p1,p2,p3}->ptList]
>{p1->{1,1,2}, p2->{2,1,3}, p3->{1,3,2}}
>
>RijArray = Outer[Rij,{p1,p2,p3},{p1,p2,p3}];
>(gives output in terms of symbols p1, p2, and p3)
>
>Then replace the symbolic points by numerical
>points, and give it a hand with Dot[0,0]:
>
>RijNbrs = RijArray /.toNbrs /. Sqrt[0 . 0]->0;
>
>The answer is, as desired,
>
>{{ 0, Sqrt[2], 2 },
> {Sqrt[2], 0, Sqrt[6]},
> { 2, Sqrt[6], 0 }}
>
>But this gets out of hand when ptList is long.
Actually, this method will work with an arbitrary number of vectors,
with a little bit of tweaking.
Try this:
Rij[a_,b_]:=Sqrt[(a-b).(a-b)]
ptList={{1,1,2},{2,1,3},{1,3,2}}
vectors=Table[p[i],{i,Length[ptList]}]
toNbrs=Thread[vectors->ptList]
RijArray=Outer[Rij,vectors,vectors]
RijNbrs=RijArray/.toNbrs/.Sqrt[0 . 0]->0
The trick, of course, is to replace your list {p1,p2,p3} with a list
of an aribitrary number of variables. p[1],p[2],p[3],... does the
trick. You might want to add a Clear[p] afterwards if you had a large
number of vectors and thus used a large number of p's.
There _should_ be a more elegant way of doing this, but I
don't know how.
>Also, with explicit indices I could cut the number of
>multiplies more than in half, because I know the
>result will be symmetric, with only zeroes on the
>diagonal. Is there some way to include this
>knowledge in a functionally programmed version?
Again, not that I know of.
/
:@-) Scott
\
http://student_97ffa.williams.edu/~shill