File Exchange

image thumbnail

Traveling Salesman Problem - Nearest Neighbor

version (8.44 KB) by Joseph Kirk
Finds a near-optimal solution to a TSP using Nearest Neighbor (NN)


Updated 06 May 2014

View License

TSP_NN Traveling Salesman Problem (TSP) Nearest Neighbor (NN) Algorithm
The Nearest Neighbor algorithm produces different results depending on
which city is selected as the starting point. This function determines
the Nearest Neighbor routes for multiple starting points and returns
the best of those routes
1. A single salesman travels to each of the cities and completes the
route by returning to the city he started from
2. Each city is visited by the salesman exactly once

USERCONFIG (structure) with zero or more of the following fields:
- XY (float) is an Nx2 matrix of city locations, where N is the number of cities
- DMAT (float) is an NxN matrix of point to point distances/costs
- POPSIZE (scalar integer) is the size of the population (should be <= N)
- SHOWPROG (scalar logical) shows the GA progress if true
- SHOWRESULT (scalar logical) shows the GA results if true
- SHOWWAITBAR (scalar logical) shows a waitbar if true

Input Notes:
1. Rather than passing in a structure containing these fields, any/all of
these inputs can be passed in as parameter/value pairs in any order instead.
2. Field/parameter names are case insensitive but must match exactly otherwise.

RESULTSTRUCT (structure) with the following fields:
(in addition to a record of the algorithm configuration)
- OPTROUTE (integer array) is the best route found by the algorithm
- MINDIST (scalar float) is the cost of the best route

resultStruct = tsp_nn;
resultStruct = tsp_nn(userConfig);
[...] = tsp_nn('Param1',Value1,'Param2',Value2, ...);

% Let the function create an example problem to solve

% Request the output structure from the solver
resultStruct = tsp_nn;

% Pass a random set of user-defined XY points to the solver
userConfig = struct('xy',10*rand(50,2));
resultStruct = tsp_nn(userConfig);

% Pass a more interesting set of XY points to the solver
n = 100;
phi = (sqrt(5)-1)/2;
theta = 2*pi*phi*(0:n-1);
rho = (1:n).^phi;
[x,y] = pol2cart(theta(:),rho(:));
xy = 10*([x y]-min([x;y]))/(max([x;y])-min([x;y]));
userConfig = struct('xy',xy);
resultStruct = tsp_nn(userConfig);

% Pass a random set of 3D (XYZ) points to the solver
xyz = 10*rand(50,3);
userConfig = struct('xy',xyz);
resultStruct = tsp_nn(userConfig);

% Turn off the plots but show a waitbar
userConfig = struct('showProg',false,'showResult',false,'showWaitbar',true);
resultStruct = tsp_nn(userConfig);

Comments and Ratings (11)

@joseph: can I make the XY coordinates as functions which will vary with another parameter like time

Joseph Kirk

@Thayjes, this function is not designed to guarantee you a solution that contains no self-intersections. In fact, most NN solutions will contain several self-intersections due to the greedy nature of the algorithm.

Hi, I have a question. I am trying to use this code to remove self intersections in a polygon by reordering the points in which I connect them. I was wondering what sort of inputs I should give for the other parameters ( apart from the x and y co-ordinates of the points), as I am only interested in the order of the points and not an optimal or route of minimum cost.

The code is amazing. The coder is a life saver. But please tell me how to specify the xy coordinates in the code as I'm a novice in matlab. Please!!!!



@Joseph: OK it works fine. I was not sure wich coordinates to use in XY.

Joseph Kirk

@Julien, it is already generalized (other than the figure displays, which you can turn off). Regardless of the dimensionality, the cost/distance matrix will be NxN, and it is this matrix that the algorithm operates on. So the algorithm really is agnostic to the number of dimensions.


Thanks for the algorithm! It works very well.
Are you planning to implement it with higher dimensions ? N=4,5,6 ...


Pretty nice program. However, there is a small bug in line 103 when by any chance two points are at the same distance min_d. Easily solvable though by just adding a line to choose the first element of J in case length(J)>1. Otherwise, works flawlessly.

Kururunfa Goju

Very nice. It could benefit from the fact of working with TSPLIB files...


Major overhaul of input/output interface.

Minor cosmetic updates.

Added 3D capability.

MATLAB Release Compatibility
Created with R2014a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired by: Traveling Salesman Problem - Genetic Algorithm