More tests + GUI
[ltsps.git] / generateDistanceMatrix.m
blobccccb9a31474979ed4ee58a7e807b2143e131d10
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>
5 % date: 30 Sep 2008
7 % Sort the matrix by first row (key)
8 sorted = sortrows(coordMatrix,1);
10 % How many nodes?
11 matrixSize = size(sorted);
12 nCities = matrixSize(1);
14 % Preallocation to prevent in-loop growing
15 distanceMatrix = zeros(nCities,nCities);
17 for i = 1:nCities
18         % coords of first city
19         x1 = sorted(i,2);
20         y1 = sorted(i,3);
21         % location vector of the first city
22         c1 = [x1 y1];
23     
24     for j = i:nCities
25         % 1:nCities would be stupid -- we'd recalculate the 1->i stuff
26         % which we already calculated in the previous loop.
27         
28         % Where is the second city?
29             % coords of the second city
30             x2 = sorted(j,2);
31             y2 = sorted(j,3);
32             % location vector of the second city
33             c2 = [x2 y2];
34         
35         % Where is the second city relative to the first?
36             % vector from c1 to c2
37             c12vec = c2 - c1;
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);
41             
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
50 end % function