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