Message Boards Message Boards

0
|
4358 Views
|
13 Replies
|
7 Total Likes
View groups...
Share
Share this post:

Unexpected behavior of DistanceMatrix?

Posted 2 years ago

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?

13 Replies

Euclidean distance computes the distance between two points. While distance matrix computes all the distances between two sets of points.

POSTED BY: Sander Huisman
Posted 2 years ago

Massimiliano, this gives the result that you expect:

DistanceMatrix[{{a, b}, {c, d}}, DistanceFunction -> EuclideanDistance]
POSTED BY: Hans Milton

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}}
POSTED BY: Jason Biggs

Perhaps something like:

{a, b, c, d} = List /@ Sqrt[{0, 2, 2, 0}]
DistanceMatrix[{{a, b}, {c, d}}]

?

POSTED BY: Sander Huisman

@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.

POSTED BY: Jason Biggs

Sorry my bad, I misread the question…

POSTED BY: Sander Huisman
Posted 2 years ago

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:

enter image description here

POSTED BY: Hans Milton

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.

Sander: no, I was really interested in computing the matrix of distances between symbolic vectors but I wasn't able to.

Posted 2 years ago

Yes, I agree it is a bit strange. But Simplify cleans it up:

DistanceMatrix[{{a, b}, {c, d}}, DistanceFunction -> EuclideanDistance] // Simplify
POSTED BY: Hans Milton

This is to take care of complex numbers…

POSTED BY: Sander Huisman

Aah I see now, yes, by default it does HammingDistance for this type of input data rather than Euclidean distance. Set the DistanceFunction option.

POSTED BY: Sander Huisman

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.

POSTED BY: Sander Huisman
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract