Deegroller

GetRoute

Jul 24th, 2012
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 2.33 KB | None | 0 0
  1. % Programming in Engineering
  2. % PiE CTW-MSM 19158510
  3. % Exam MATLAB (2012) Exercise 2.1
  4. % Joris Janssen s0165778
  5.  
  6. function Route = GetRoute( CityCoordinates )
  7. %GETROUTE Calculates a short route between a large (> 10) number of cities.
  8. %   This function tries to find a reasonably short route that can be used
  9. %   as a starting point for other further optimized functions. The route is
  10. %   computed by sort of implementing a nearest neighbour method, by looking for the nearest city and travelling to that, until
  11. %   all cities are visited.
  12. %
  13. %   Input: CityCoordinates, a N-by-2 matrix containing the X and Y coordinates
  14. %   as columns for N cities. Note that this excludes the first city since the
  15. %   first city is located at (0,0) and all other coordinates are relative to
  16. %   the first city. Either type out the matrix by hand or use the function
  17. %   GetCities(N) to read out a textfile with city coordinates.
  18. %
  19. %   Output: Outputs a reasonable short route as a row vector.
  20.  
  21. % Notes on performance: This implementation is rather crude. It computes
  22. % every route
  23. %
  24.  
  25. tic; % Starts a timer to measure the execution time of the script
  26.  
  27. N = length(CityCoordinates) ;    % The number of cities, retrieved by reading matrix CityCoordinates
  28. Route = ones(1,N+1);             % Pre-allocation of Route
  29.  
  30. % First look at your current position, inital value 1.
  31. location = 1;
  32. % Next look at which cities are nearby
  33. nearbyCities = 2:N;
  34.  
  35. for (j=2:1:N)
  36. % Now compute the distance to every allowable city
  37. % Every city that is not 1 and has not yet been visited is allowable
  38. % Visited cities are removed from the possibilities at the end of the first
  39. % loop
  40. neighbours = length(nearbyCities);
  41. clear Trip; % Trip has to be cleared before each loop, it shrinks every loop since the number of possibilities d
  42.     for (i=1:1:neighbours)
  43.         nearbyCity = nearbyCities(i);
  44.         Trip(i , 1:2) = [location, nearbyCity];
  45.         Trip(i , 3) = CalculateDistance(CityCoordinates,location,nearbyCity);
  46.     end
  47.    
  48. % We now have a matrix
  49. [shortestDistance,ind] = min(Trip(:,3));
  50. nearestCity = Trip(ind,2);
  51. location = nearestCity;
  52.  
  53. % Now remove the city from the list of possibilities
  54. indexToBeRemoved = find(nearbyCities==nearestCity);
  55. nearbyCities( indexToBeRemoved ) = [];
  56. Route(1,j) = nearestCity;
  57. end
  58. exetime = toc % Execution time in seconds
  59. end
Advertisement
Add Comment
Please, Sign In to add comment