Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.38 KB | None | 0 0
  1. function pathLength = GetNearestNeighbourPathLength(cityLocation)
  2.   pathLength = 0;
  3.   nCities = length(cityLocation);
  4.   visitedIxs = [1];
  5.   firstCity = cityLocation(1, :);
  6.  
  7.   for i=2:nCities
  8.     currentCityIx = visitedIxs(end);
  9.     % calculate distance from this node to every other and sort them
  10.     distances = CalculateDistances(currentCityIx, cityLocation);
  11.     [sortedDistances, indices] = sort(distances);
  12.  
  13.     % increment index until we find the closest unvisited neighbour
  14.     closestUnvisitedIx = 1;
  15.     while ismember(indices(closestUnvisitedIx), visitedIxs)
  16.       closestUnvisitedIx = closestUnvisitedIx + 1;
  17.     end
  18.  
  19.     % add the closest unvisited neighbour to the visited list and
  20.     % add the distance to the total path length
  21.     visitedIxs = [visitedIxs; indices(closestUnvisitedIx)];
  22.     pathLength = pathLength + sortedDistances(closestUnvisitedIx);
  23.   end
  24.  
  25.   % add the length of the final step
  26.   lastCity = cityLocation(visitedIxs(end), :);
  27.   finalStepLength = pdist([firstCity; lastCity], 'euclidean');
  28.   pathLength = pathLength + finalStepLength;
  29.  
  30. end
  31.  
  32. function distances = CalculateDistances(fromIx, cityLocation)
  33.   distances = [];
  34.   origin = cityLocation(fromIx, :);
  35.  
  36.   for i=1:length(cityLocation)
  37.     thisCityLocation = cityLocation(i, :);
  38.     distance = pdist([origin; thisCityLocation], 'euclidean');
  39.     distances = [distances; distance];
  40.   end
  41. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement