Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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"}]]
share|improve this question
    
Does this help? –  Szabolcs Sep 30 '13 at 20:51
1  
@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

1 Answer 1

up vote 7 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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