# Calculating the distance between the coordinates in a list

I have a list of coordinates

{{A[9, 4, 7], 0.0395174}, {A[1, 5, 0], 0.0163797}, {A[0, 7, 2], 0.0577425},
{A[2, 7, 5], 1.01313}}


I want to find the distance between them using the equation

$$r= \sqrt{(x_2-x_1 )^2+ (y_2-y_1)^2+(z_2-z_1)^2 }$$

I will choose the first coordinate and calculate the distance to other coordinates by using the above equation. In the second step I will take the second coordinate and calculate the distance to other coordinates. since the distance between first one and second one is already calculated there is no need to do it again. In this way I have to find the distance between all coordinates. Can anyone help me.

-

Essentially you have a number of points, lets say 1 to 4, and you want the distance corresponding to every subset containing two points, so first lets calculate the indexes using SubSets[]

 Subsets[Range[4], {2}]

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


This gives you all the different distances to calculate, now to carry this out, we simply create a function to return the distance and map it over these subsets (naturally using the actual length of our inputs.

list = {{A[9, 4, 7], 0.0395174}, {A[1, 5, 0], 0.0163797}, {A[0, 7, 2],
0.0577425}, {A[2, 7, 5], 1.01313}} // N;
distanceBetween[{n_, m_}] := Norm[List @@ list[[n, 1]] - List @@ list[[m, 1]]]
distanceBetween /@ Subsets[Range[Length[list]], {2}]


If you want a function to carry all this out, then I think this looks somewhat nice.

distanceBetween[list_][{n_, m_}] := Norm[List @@ list[[n, 1]] - List @@ list[[m, 1]]]
distances[list_] := distanceBetween[list] /@ Subsets[Range[Length[list]], {2}]

-

There is also the built-in function EuclideanDistance.

To get the distance between kth and mth elements in list, use as:

EuclideanDistance @@ list[[{k, m}]]


To get distances between all pairs of elements in list, use as:

EuclideanDistance @@@ Subsets[list, {2}]


Example:

list = RandomReal[{0, 1}, {5, 3}]
(* {{0.448481, 0.113175, 0.378866}, {0.95328, 0.155569, 0.767866},
{0.557744, 0.317193, 0.96725}, {0.484059, 0.177696, 0.781731},
{0.647812, 0.312039, 0.13098}} *)
EuclideanDistance @@ list[[{1, 2}]]
(*  0.638702 *)
EuclideanDistance @@@ Subsets[list, {2}]
(* {0.638702, 0.632264, 0.409547, 0.375136, 0.471513, 0.469947, 0.723476, 0.243529, 0.841122, 0.684354} *)


Organized in tabular form:

Thread[{Subsets[Range@Length@list, {2}], Subsets[list, {2}],
EuclideanDistance @@@ Subsets[list, {2}]}] //
TableForm[#, TableHeadings -> {None, {"points", "coordinates", "distance"}}] &


-