# Distances of locations in the matrix form

I want to have the distances of the cities in the matrix form.How can I have it for example for the cities like followings that also includes the distance of the city from itself which is zero:

Union[#[] -> #[] & /@
Permutations[CityData[{Large, "Germany"}], {2}], # -> # & /@
CityData[{Large, "Germany"}]]

• Does this help? – Szabolcs Sep 30 '13 at 20:51
• @Szabolcs No, because the distance to be used here is GeoDistance, where tricks such as vectorization, Tr, compile, etc. won't work. – rm -rf Sep 30 '13 at 20:58
• @rm-rf Actually the question (not answer) I linked to gives a non-Eculidean example using Outer, which is the simplest possible solution to the OP's problem. – Szabolcs Oct 1 '13 at 2:25
• @Szabolcs Ah, didn't see your example in the question (which is basically what my answer is). All the answers seemed to focus on tricks for Manhattan/Euclidean, which is what my comment was referring to. – rm -rf Oct 1 '13 at 2:30

I'm not quite sure what you mean by distances in "diagonal matrix" form. Pairwise distances are certainly displayed as matrices, but these are not diagonal (they're symmetric, with zeros along the diagonal). In any case, here's a way to obtain that. I'll define a function cityData that returns the great-circle distance between two cities:

ClearAll@cityDistance
SetAttributes[cityDistance, Orderless]
cityDistance[x_, y_] := cityDistance[x, y] =
GeoDistance @@ (CityData[#, "Coordinates"] & /@ {x, y})


The Orderless attribute is used, because the distance from A to B is the same as from B to A.

Then, with your list of cities:

cities = CityData[{Large, "Germany"}]
(* {{"Berlin", "Berlin", "Germany"}, {"Hamburg", "Hamburg", "Germany"},
{"Munich", "Bavaria", "Germany"}, {"Cologne", "NorthRhineWestphalia", "Germany"}, ...} *)


you can form a matrix of pair-wise distances as:

distanceMatrix = Outer[cityDistance, cities, cities, 1];


which gives the distance in meters.