masspav
(Massimiliano Pavan)
July 31, 2022, 11:11pm
1
I’m trying to use DistanceMatrix to compute the matrix of pairwise distances between two generic vectors (a,b) and (c,d) in the following way:
I really can’t understand the result. Comparing to EuclideanDistance as follows:
I would expect the following result or something like that:
where am I wrong?
sghuisman
(Sander Huisman)
August 1, 2022, 3:17am
2
Euclidean distance computes the distance between two points. While distance matrix computes all the distances between two sets of points.
Massimiliano, this gives the result that you expect:
DistanceMatrix[{{a, b}, {c, d}}, DistanceFunction -> EuclideanDistance]
jasonb
(Jason Biggs)
August 1, 2022, 2:46pm
4
I still don’t understand in what universe the following makes sense:
In[1]:= DistanceMatrix[{{a, b}, {c, d}}]
Out[1]= {{0, 2}, {2, 0}}
sghuisman
(Sander Huisman)
August 1, 2022, 3:26pm
5
Perhaps something like:
{a, b, c, d} = List /@ Sqrt[{0, 2, 2, 0}]
DistanceMatrix[{{a, b}, {c, d}}]
?
jasonb
(Jason Biggs)
August 1, 2022, 3:35pm
6
@Sander Huisman input/output does make sense, but it isn’t the same example though. DistanceMatrix seems to return numeric output from purely symbolic input.
sghuisman
(Sander Huisman)
August 1, 2022, 3:36pm
7
Sorry my bad, I misread the question…
Jason, the universe that you are looking for is the one that has the HammingDistance as a metric. Which in MMA is the default for symbolic vector input. Counting the number of inequalities between vector elements. From documentation :
masspav
(Massimiliano Pavan)
August 1, 2022, 11:39pm
9
Thanks Hans, it works!
However it seems strange to me that DistanceMatrix adds an unnecessary (I think) Abs function under the square root:
As you can see, this happens using both EuclideanDistance and SquaredEuclideanDistance as distance function. I don’t know if there is any mathematical or implementative reason for that.
masspav
(Massimiliano Pavan)
August 1, 2022, 11:49pm
10
Sander: no, I was really interested in computing the matrix of distances between symbolic vectors but I wasn’t able to.
hansmilton
(Hans Milton)
August 2, 2022, 7:31am
11
Yes, I agree it is a bit strange. But Simplify cleans it up:
DistanceMatrix[{{a, b}, {c, d}}, DistanceFunction -> EuclideanDistance] // Simplify
sghuisman
(Sander Huisman)
August 2, 2022, 7:48am
12
This is to take care of complex numbers…
sghuisman
(Sander Huisman)
August 2, 2022, 7:49am
13
Aah I see now, yes, by default it does HammingDistance for this type of input data rather than Euclidean distance. Set the DistanceFunction option.
sghuisman
(Sander Huisman)
August 2, 2022, 7:01pm
14
Perhaps more efficient is to use a substitution (though for 2x2 it doesn’t matter):
DistanceMatrix[{{a, b}, {c, d}}, DistanceFunction -> EuclideanDistance]
% //. Abs[x_] :> x
if you know for sure that a,b,c, and d are real numbers.