({{, (RefLink[DistanceMatrix, paclet:ref/DistanceMatrix])[{(Subscript[u, 1]),(Subscript[u, 2]),…}]
gives the matrix of distances between each pair of elements (Subscript[u, i]), (Subscript[u, j]). }, {, (RefLink[DistanceMatrix, paclet:ref/DistanceMatrix])[{(Subscript[u, 1]),(Subscript[u, 2]),…},{(Subscript[v, 1]),(Subscript[v, 2]),…}]
gives the matrix of distances between each pair of elements (Subscript[u, i]), (Subscript[v, j]).}})

OpenersNotesSection(Spacer1)Details and Options

(RefLink[DistanceMatrix, paclet:ref/DistanceMatrix]) works for a variety of data, including numerical, geospatial, textual, visual, dates and times, as well as combinations of these.

Each (Subscript[u, i]) can be a single data element, a list of data elements or an association of data elements. In (RefLink[DistanceMatrix, paclet:ref/DistanceMatrix])[data,…], data can also be a (RefLink[Dataset, paclet:ref/Dataset]) object.

The following options can be given:

The setting for (RefLink[DistanceFunction, paclet:ref/DistanceFunction]) can be any distance or dissimilarity function or a function f defining a distance between two values.

By default, the following distance functions are used for different types of elements:

All images are first conformed using (RefLink[ConformImages, paclet:ref/ConformImages]).

By default, when data elements are mixed-type vectors, distances are computed independently for each type and combined using (RefLink[Norm, paclet:ref/Norm]).

Possible settings for (RefLink[PerformanceGoal, paclet:ref/PerformanceGoal]) include:

Possible settings for (RefLink[RandomSeeding, paclet:ref/RandomSeeding]) include:

OpenersPrimaryExamplesSection(Spacer1)Examples  (22)

OpenersExampleSection0(Spacer1)Basic Examples  (3)

Compute a distance matrix from a list of integers:

dm=DistanceMatrix[{1,2,3,4}]

dm // MatrixForm

Compute a distance matrix from two lists of integers:

dm=DistanceMatrix[{1,2,3,4}, {5,6,7}]

dm // MatrixForm

Compute a distance matrix from real-valued numerical vectors:

dm=DistanceMatrix[{{1.5,4.3},{2.1,5.6},{6.2,4.5}},{{1.6,4.2},{2.3,5.4}}]

dm // MatrixForm

OpenersExampleSection1(Spacer1)Scope  (10)

Compute a distance matrix from images:

DistanceMatrix[{,,}] // MatrixForm

Compute a distance matrix from strings:

DistanceMatrix[{"abcd","bcde","xyz"}] // MatrixForm

Compute a distance matrix from Boolean vectors:

DistanceMatrix[{{True,False,True},{True,True,True},{True,False,False}}] // MatrixForm

Compute a distance matrix from a list of date objects:

DistanceMatrix[{DateObject[{1985,10,3}], DateObject[{1989,5,30}],DateObject[]}] // MatrixForm

Compute a distance matrix from geodetic positions:

DistanceMatrix[{GeoPosition[(Entity["Paris", Entity["City",{"Paris","IleDeFrance","France"}], "Entity[\"City\", {\"Paris\", \"IleDeFrance\", \"France\"}]", "city"])],GeoPosition[(Entity["Sydney", Entity["City",{"Sydney","NewSouthWales","Australia"}], "Entity[\"City\", {\"Sydney\", \"NewSouthWales\", \"Australia\"}]", "city"])],GeoPosition[(Entity["Boston", Entity["City",{"Boston","Massachusetts","UnitedStates"}], "Entity[\"City\", {\"Boston\", \"Massachusetts\", \"UnitedStates\"}]", "city"])],GeoPosition[(Entity["San Francisco", Entity["City",{"SanFrancisco","California","UnitedStates"}], "Entity[\"City\", {\"SanFrancisco\", \"California\", \"UnitedStates\"}]", "city"])]}] // MatrixForm

Compute a distance matrix from nominal sequences:

DistanceMatrix[{{"a","b","c","d"},{"b","c","d","e"},{"x","y","z"}}] // MatrixForm

Compute a distance matrix from numerical sequences:

DistanceMatrix[{{1.1,1.2,1.3,1.4,1.5},{1.2,1.3},{1.4,1.5,1.6}}] // MatrixForm

Compute a distance matrix on nominal vectors:

DistanceMatrix[{{"A","Sugar"},{"A","Salt"},{"B","Sugar"},{"B","Salt"}}]//MatrixForm

Compute a distance matrix from mixed-type vectors:

DistanceMatrix[{{1.2, "A"},{3.1,"A"}, {1.1,"B"},{3.3,"B"}}] // MatrixForm

Compute a distance matrix from a dataset formatted as a list of associations:

data={<|"age"->32,"height"->160, "gender"-> "female"|>,
<|"height"->183,"age"->41,"gender"-> "female"|>,
<|"height"->123,"age"->30,"gender"-> "female"|>,
<|"height"->175,"age"->21,"gender"-> "male"|>,
<|"height"->150,"age"->11,"gender"-> "male"|>,
<|"age"->52,"height"->164,"gender"-> "female"|>};

DistanceMatrix[data]//MatrixForm

Compute the same distance matrix with a column-oriented dataset:

DistanceMatrix[\[LeftAssociation]"age"->{32,41,30,21,11,52},"height"->{160,183,123,175,150,164},"gender"->{"female","female","female","male","male","female"}\[RightAssociation]]//MatrixForm

Data can also be given in a (RefLink[Dataset, paclet:ref/Dataset]) object:

dataset=Dataset[data]

DistanceMatrix[dataset]//MatrixForm

OpenersExampleSection2(Spacer1)Options  (8)

OpenersExampleSubsection0(Spacer1)DistanceFunction  (2)

Compute a distance matrix from integer vectors using (RefLink[SquaredEuclideanDistance, paclet:ref/SquaredEuclideanDistance]) as a distance function:

DistanceMatrix[{{1,5},{2,3},{3,1},{4,7}}, DistanceFunction->SquaredEuclideanDistance] // MatrixForm

Compute a distance matrix with the (RefLink[ManhattanDistance, paclet:ref/ManhattanDistance]):

DistanceMatrix[{{1.3,5.2},{1.2,7.3},{3.6,1.1},{4.6,7.4}}, DistanceFunction->ManhattanDistance] // MatrixForm

OpenersExampleSubsection1(Spacer1)FeatureExtractor  (1)

Compute a distance matrix from images preprocessed by the feature extractor method "NumericVector":

DistanceMatrix[{,,,,,},FeatureExtractor->"NumericVector"] // MatrixPlot

OpenersExampleSubsection2(Spacer1)FeatureNames  (1)

Use (RefLink[FeatureNames, paclet:ref/FeatureNames]) to name features, and refer to their names in further specifications:

DistanceMatrix[{{2.3,"male"},{4.8,Missing[]},{Missing[],"female"},{5.2,"female"}}, FeatureNames->{"gender","age"}, FeatureTypes-><|"gender"->"Numerical","age"->"Nominal"|>]

OpenersExampleSubsection3(Spacer1)FeatureTypes  (1)

Use (RefLink[FeatureTypes, paclet:ref/FeatureTypes]) to enforce the interpretation of the first feature as nominal:

DistanceMatrix[{{1,"A"},{2,"A"},{2,"B"},{1,"B"}},FeatureTypes-><|1->"Nominal"|>]// MatrixForm

OpenersExampleSubsection4(Spacer1)PerformanceGoal  (1)

Generate 2000 random numerical vectors of length 1000:

vectors=RandomReal[{10,11},{2000,1000}];

Compute their distance matrix and benchmark the operation:

AbsoluteTiming[result = DistanceMatrix[vectors];]

Perform the same operation with (RefLink[PerformanceGoal, paclet:ref/PerformanceGoal]) set to "Speed":

AbsoluteTiming[resultspeed=DistanceMatrix[vectors,PerformanceGoal->"Speed"];]

Compare timing and accuracies of the previous results with a reference:

AbsoluteTiming[reference=Outer[EuclideanDistance,vectors,vectors,1];]

StandardDeviation[Flatten[result-reference]]

StandardDeviation[Flatten[resultspeed-reference]]

When (RefLink[PerformanceGoal, paclet:ref/PerformanceGoal])->"Speed", centering the data can increase the precision:

mean= Mean[vectors];
centered = #-mean & /@ vectors;

AbsoluteTiming[resultspeedcentered=DistanceMatrix[centered,PerformanceGoal->"Speed"];]

StandardDeviation[Flatten[resultspeedcentered-reference]]

OpenersExampleSubsection5(Spacer1)RandomSeeding  (1)

(RefLink[DistanceMatrix, paclet:ref/DistanceMatrix]) gives the same result when evaluated multiple times, even when randomness is involved.

Generate a pair of 20-dimensional vectors:

data = RandomReal[1, {2,20}];

Compute its distance matrix several times using a feature extractor involving randomness:

table = Table[DistanceMatrix[data, FeatureExtractor->(RandomChoice[#, 10]&)], 5];

Compare the results:

Counts[table]

Use different values for the (RefLink[RandomSeeding, paclet:ref/RandomSeeding]) option to compute the distance matrices:

randomtable = Table[DistanceMatrix[data, FeatureExtractor->(RandomChoice[#, 10]&), RandomSeeding->RandomInteger[10]], 5];

Compare the results:

Counts[randomtable]

OpenersExampleSubsection6(Spacer1)WorkingPrecision  (1)

Compute the distance matrix for 500 random numerical vectors of length 100 that have a precision of 30:

r=RandomReal[1,{500, 100}, WorkingPrecision->30];

AbsoluteTiming[dm=DistanceMatrix[r];]

(RefLink[DistanceMatrix, paclet:ref/DistanceMatrix]) uses arbitrary-precision computation:

Precision[dm]

Using (RefLink[WorkingPrecision, paclet:ref/WorkingPrecision])->(RefLink[MachinePrecision, paclet:ref/MachinePrecision]) can speed up the computation:

AbsoluteTiming[dmmachine=DistanceMatrix[r,WorkingPrecision->MachinePrecision];]

But the results are not as precise:

Precision[dmmachine]

When vectors are similar, changing the value of (RefLink[WorkingPrecision, paclet:ref/WorkingPrecision]) can lead to significantly different results:

r=RandomReal[{10^20,10^20+1},{3, 2}, WorkingPrecision->30]

DistanceMatrix[r] // MatrixForm

DistanceMatrix[r, WorkingPrecision->MachinePrecision] // MatrixForm

OpenersExampleSection3(Spacer1)Applications  (1)

Find the minimum distance between two sets of points:

p1=RandomPoint[Sphere[],20];
p2=RandomPoint[Sphere[{3,2,5}],20];
ListPointPlot3D[{p1,p2}, AspectRatio->1]

Min[DistanceMatrix[p1,p2]]

({{DocumentationFooterIconsRelatedFunction.png, ({{See Also}, {(RefLink[Outer, paclet:ref/Outer])  ▪  (RefLink[NearestNeighborGraph, paclet:ref/NearestNeighborGraph])  ▪  (RefLink[AdjacencyMatrix, paclet:ref/AdjacencyMatrix])  ▪  (RefLink[GraphDistanceMatrix, paclet:ref/GraphDistanceMatrix])  ▪  (RefLink[Nearest, paclet:ref/Nearest])  ▪  (RefLink[Norm, paclet:ref/Norm])  ▪  (RefLink[ClusterClassify, paclet:ref/ClusterClassify])  ▪  (RefLink[FindClusters, paclet:ref/FindClusters])  ▪  (RefLink[DistanceFunction, paclet:ref/DistanceFunction])}})}})

({{DocumentationFooterIconsRelatedGuide.png, ({{Related Guides}, {▪(RefLinkPlain[Distance and Similarity Measures, paclet:guide/DistanceAndSimilarityMeasures])}, {▪(RefLinkPlain[Operations on Vectors, paclet:guide/OperationsOnVectors])}, {▪(RefLinkPlain[Sequence Alignment & Comparison, paclet:guide/SequenceAlignmentAndComparison])}, {▪(RefLinkPlain[Text Analysis, paclet:guide/TextAnalysis])}})}})