# Computing distance matrix for a list

Using functional programming in Mathematica, how can I compute a distance matrix for every element in a list of matrices... The distance would be computed between the item in the list and a "target matrix". For simplicity, let's consider that the list is a list of simple 3x2 matrices of integer with a range [0,4]. The target matrix is a matrix of that type as well. The reason I want to do that is to filter the list to find the matrix closest to the target one.

-

(* source matrices *)
as = RandomInteger[{0, 4}, {10, 2, 2}]


{{{2, 2}, {3, 2}}, {{2, 4}, {3, 3}}, {{1, 4}, {1, 3}}, {{2, 1}, {4, 4}}, {{2, 4}, {2, 0}}, {{3, 3}, {1, 2}}, {{1, 2}, {1, 0}}, {{4, 1}, {0, 4}}, {{2, 4}, {0, 2}}, {{1, 3}, {2, 0}}}

(* Target matrix *)
b = {{1, 1}, {1, 1}}

Plus @@ Abs@Flatten@(# - b) & /@ as


{5, 8, 5, 7, 6, 5, 2, 7, 6, 4}

If you prefer to use EuclideanDistance as a metric you can apply the following:

EuclideanDistance[b, #] & /@ as //N


{2.61803, 4.13065, 3.60555, 4.30278, 3.23607, 2.92081, 1.41421, 3.54138, 3.23607, 2.28825}

-
One might prefer to use a matrix norm for distances, e.g. N[Norm[# - b, "Frobenius"] & /@ as]. Pick[] can then be used: Pick[as, %, Min[%]]. – J. M. Apr 16 '13 at 11:25
@J.M. Yes that would be a good solution. – image_doctor Apr 16 '13 at 11:32

If the purpose is as in the following,

The reason I want to do that is to filter the list to find the matrix closest to the target one,

then an alternative would be to use Nearest:

SeedRandom[2013];
matlist = RandomInteger[{0, 4}, {100, 3, 2}];
dist[m1_, m2_] := Norm[m1 - m2, "Frobenius"];
nf = Nearest[matlist, DistanceFunction -> dist];

nf[{{3, 1}, {2, 1}, {1, 3}}]
(* {{{2, 1}, {1, 0}, {0, 3}}} *)

Position[matlist, First@nf[{{3, 1}, {2, 1}, {1, 3}}]]
(* {{9}} *)

-
Alternatively, one can do nf = Nearest[matlist -> Automatic, DistanceFunction -> dist], so that the NearestFunction[] returns the index of the nearest matrix instead of the matrix itself. One can then use Part[] or Extract[] to get the actual matrix afterwards. – J. M. Apr 16 '13 at 14:31
Thanks for this, I will investigate this path as well :) – afentis Apr 18 '13 at 7:32