1 function distanceMatrix = generateDistanceMatrix (coordMatrix)
2 % generateDistanceMatrix
3 % description: Generates a distance matrix from a matrix of coordinates.
4 % author: Laurens Van Houtven <lvh@laurensvh.be>
7 % Sort the matrix by first row (key)
8 sorted = sortrows(coordMatrix,1);
11 matrixSize = size(sorted);
12 nCities = matrixSize(1);
14 % Preallocation to prevent in-loop growing
15 distanceMatrix = zeros(nCities,nCities);
18 % coords of first city
21 % location vector of the first city
25 % 1:nCities would be stupid -- we'd recalculate the 1->i stuff
26 % which we already calculated in the previous loop.
28 % Where is the second city?
29 % coords of the second city
32 % location vector of the second city
35 % Where is the second city relative to the first?
36 % vector from c1 to c2
38 % How farm is the second city from the first?
39 % distance from c1 to c2 is the norm of the vector between them
40 c12dist = norm(c12vec);
42 % Save those distances.
43 % add the distance to the matrix
44 distanceMatrix(i,j) = c12dist;
45 % when in doubt, problem is symmetric
46 distanceMatrix(j,i) = c12dist;
47 end % inner for, distances for city j are done
48 end % outer for, distances for city i are done