       Re: Functional programming puzzle

• To: mathgroup at christensen.cybernetics.net
• Subject: [mg1880] Re: Functional programming puzzle
• From: el at qua.crl.melco.co.jp (E. Lange)
• Date: Sat, 12 Aug 1995 22:49:57 -0400

```>Dear functional programers:
>
>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]
>
>But Mathematica returns a mess, because Outer seems
>to Flatten the ptList before running the outer
>product loops.

A ``oneliner'' solution (using (x-y)^2 = x^2 + y^2 - 2xy) would be

dist[A_] := Sqrt[ #.#&/@A + Transpose[#.#&/@A - 2 A . Transpose[A]] ]

It runs also faster than other proposed solutions:

A = Table[Random[], {25}, {25}];
ptList = point @@ # & /@ A;

Timing[dist[A];]
(* {0.433333 Second, Null} *)

Timing[Outer[distance,ptList,ptList];]
(* {9.33333 Second, Null} *)

Timing[Distances[ptList];]
(* {4.6 Second, Null} *)

( The readable expression for #.#&/@A is Map[sumSquare, A], with
sumSquare[a_] := a.a )

Eberhard Lange

```

• Prev by Date: Re: Double Log Plot
• Next by Date: pictures
• Previous by thread: Re: Functional programming puzzle
• Next by thread: Re: Functional programming puzzle