Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function pathLength = GetNearestNeighbourPathLength(cityLocation)
- pathLength = 0;
- nCities = length(cityLocation);
- visitedIxs = [1];
- firstCity = cityLocation(1, :);
- for i=2:nCities
- currentCityIx = visitedIxs(end);
- % calculate distance from this node to every other and sort them
- distances = CalculateDistances(currentCityIx, cityLocation);
- [sortedDistances, indices] = sort(distances);
- % increment index until we find the closest unvisited neighbour
- closestUnvisitedIx = 1;
- while ismember(indices(closestUnvisitedIx), visitedIxs)
- closestUnvisitedIx = closestUnvisitedIx + 1;
- end
- % add the closest unvisited neighbour to the visited list and
- % add the distance to the total path length
- visitedIxs = [visitedIxs; indices(closestUnvisitedIx)];
- pathLength = pathLength + sortedDistances(closestUnvisitedIx);
- end
- % add the length of the final step
- lastCity = cityLocation(visitedIxs(end), :);
- finalStepLength = pdist([firstCity; lastCity], 'euclidean');
- pathLength = pathLength + finalStepLength;
- end
- function distances = CalculateDistances(fromIx, cityLocation)
- distances = [];
- origin = cityLocation(fromIx, :);
- for i=1:length(cityLocation)
- thisCityLocation = cityLocation(i, :);
- distance = pdist([origin; thisCityLocation], 'euclidean');
- distances = [distances; distance];
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement