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[#[[1]] -> #[[2]] & /@ 
Permutations[CityData[{Large, "Germany"}], {2}], # -> # & /@ 
CityData[{Large, "Germany"}]]
  • $\begingroup$ Does this help? $\endgroup$
    – Szabolcs
    Sep 30 '13 at 20:51
  • 1
    $\begingroup$ @Szabolcs No, because the distance to be used here is GeoDistance, where tricks such as vectorization, Tr, compile, etc. won't work. $\endgroup$
    – rm -rf
    Sep 30 '13 at 20:58
  • $\begingroup$ @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. $\endgroup$
    – Szabolcs
    Oct 1 '13 at 2:25
  • $\begingroup$ @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. $\endgroup$
    – 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:

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.