Project 1 - Traveling salesman problem
Travelling salesman problem:
citypoints=20;
x=randi(100,citypoints,1);
y=randi(100,citypoints,1);
plot(x, y, 'bo', 'MarkerSize', 10);
title('Travelling Salesman Problem');
xlabel('x-distance from the city center(in km)');
ylabel('y-distance from the city center(in km)');
grid on;
% Compute the distance of each of the city points from origin(0, 0)
distances = sqrt(x.^ 2 + y.^ 2);
% Find the nearest one.
[minDistance, indexOfMin] = min(distances);
nearestX = x(indexOfMin);
nearestY = y(indexOfMin);
initialcity = [nearestX,nearestY];
hold on;
plot(nearestX, nearestY, 'r*', 'MarkerSize', 8, 'LineWidth', 2);
%line([0, nearestX], [0, nearestY], 'LineWidth', 2, 'Color', 'r');
% Go from that point to the nearest of the other points.
cityUsed = false(1, citypoints);
counter = 2;
maxIterations = citypoints;
cityUsed(indexOfMin) = true;
fprintf('The minimum distance path is:');
fprintf('(%d %d)-->',nearestX,nearestY);
while sum(cityUsed) <= (citypoints - 1) && (counter <= maxIterations)
previousx = x(indexOfMin(counter - 1));
previousy = y(indexOfMin(counter - 1));
x(cityUsed) = inf;
distances = sqrt((x - previousx) .^ 2 + (y - previousy) .^ 2);
[minDistance, indexOfMin(counter)] = min(distances);
nearestX = x(indexOfMin(counter));
nearestY = y(indexOfMin(counter));
line([previousx, nearestX], [previousy, nearestY], 'LineWidth', 2, 'Color', 'r');
cityUsed(indexOfMin(counter)) = true;
counter = counter + 1;
fprintf('(%d %d)-->',nearestX,nearestY);
end
line([nearestX, initialcity(1)], [nearestY,initialcity(2)], 'LineWidth', 2, 'Color', 'r');
print('Travelling sales man problem','-djpeg');
OUTPUT:

The minimum distance path is:(8 47)-->(2 66)-->(1 70)-->(21 65)-->(25 77)-->(44 77)-->(38 94)-->(76 93)-->(98 95)-->(97 54)-->(96 53)-->(81 48)-->(69 38)-->(71 30)-->(70 25)-->(83 27)-->(97 10)-->(53 19)-->(53 24)-->(49 41)-->>>