How do I find the Euclidean distance between one point and all the points in a list?
I would use DistanceMatrix
for this. Here is a comparison of DistanceMatrix
with the other answers:
SeedRandom[1];
data = RandomReal[1, {10^7, 2}];
r1 = First @ DistanceMatrix[{{1., 1.}}, data]; //AbsoluteTiming
r2 = distance[{1,1}, data]; //AbsoluteTiming (* Mahdi *)
r3 = Outer[EuclideanDistance, {{1., 1.}}, data, 1] //Flatten; //AbsoluteTiming (* RunnyKine *)
r1 == r2 == r3
{0.384095, Null}
{0.88146, Null}
{9.64241, Null}
True
Here is what you want to do. Let the first point's coordinate be stored as a list of list as follows:
x1 = {{6.05102, 5.87667}}
and the second set of coordinates
y1 = {{1.40687, 4.92494}, {0.419206, 1.70406}, {6.29657,0.577941}, {4.12022, 4.94952},
{2.04784, 5.94545}, {1.29192,1.43152}, {3.26737, 1.90134}, {4.27274, 0.528028},
{2.79659,1.37788}, {5.43955, 1.81355}}
Now to compute the Euclidean distances between x1
and every element in y1
use Outer
, your best friend from now on.
Outer[EuclideanDistance, x1, y1, 1]//Flatten
This then gives you
{4.74067, 7.00914, 5.30442, 2.14187, 4.00377, 6.51217, 4.85304, 5.63651, 5.55252, 4.10887}.
Hope this helps. In fact, you can loop this through various x1's as follows.
Table[Outer[EuclideanDistance, {killer[[k]]}, y1, 1], {k, 1, n}]
Where n is the Length of the killer list. This is fast and compact code.
I understand that this question already has an accepted answer, but couldn't resist posting my answer. This answer is mainly useful if you have a very large dataset. I define the following function using Compile
function in Mathematica.
distance = Compile[{{n, _Real, 1}, {z, _Real, 2}},
Sqrt[Total[(# - n)^2]] & /@ z, RuntimeOptions -> "Speed",
Parallelization -> True, CompilationTarget -> "C",
RuntimeAttributes -> {Listable}
];
Then we map the function over a two dimensional set with 10000000 (=$10^7$) points.
data = RandomReal[{0, 1}, {10000000, 2}];
The result is:
new[{0, 0}, data] // AbsoluteTiming // First
(* 0.609684 s *)
which is 10 times faster compared to the accepted answer:
Outer[EuclideanDistance, {{0, 0}}, data, 1] // AbsoluteTiming // First
(* 5.927118 s *)