1 function totalDistance = calculateRouteDistance (route, distanceMatrix)
2 % calculateRouteDistance
3 % description: Calculates the distance travelled while following a route,
4 % given the (possibly symmetric) distance matrix (rows are sources, columns
5 % are destinations) and the route that is followed. Assumes routes are
6 % cyclic, but works fine if they're not (besides complaining a little).
7 % author: Laurens Van Houtven <lvh@laurensvh.be>
10 % Do a few rudimentary checks on input. Don't expect intelligent error
11 % messages to be returned. Set this to any true value to do the checks, any
12 % false value to disable them.
15 % What are the dimensions of the distance matrix? (or: # of cities?)
16 matrixDims = size(distanceMatrix);
17 % How many cities are there?
18 nCities = matrixDims(2);
20 % What are the dimensions of the route vector? (should be n+1)
21 routeDims = size(route);
22 % How many cities are there in the route?
23 routeSize = routeDims(2);
26 % TODO: sprintf for better error messages.
27 % Apparently this is not part of the assignment anyway, so not wasting
28 % time on this right now.
30 if matrixDims(1) ~= matrixDims(2)
31 % Danger, Will Robinson, danger! Distance matrix not square.
32 disp('The distance matrix you gave me is not square.')
35 if routeSize ~= (nCities+1)
36 % Route either has too many or too few entries!
37 disp('The route doesnt have the number of cities I was expecting.')
40 if route(1) ~= route(routeSize)
41 % Route is not cyclic!
42 disp('The last node in the given route is not the same as the first.')
48 for i = 1:(routeSize-1)
49 % routeSize-1 and nCities are equivalent and nCities is arguably
50 % slightly more elegant, but routeSize-1 makes more sense in this
51 % algorithm because we are adding the distance from nodes i to i+1
52 % every time we evaluate this loop body.
57 % Calculate the distance between i and i+1
58 newDistance = distanceMatrix(city1, city2);
59 totalDistance = totalDistance + newDistance; % matlab has no +=???