MATLAB program for TSP (similar to GA)
But not .....
Pay attention to elimination
I feel a little inspired .. Haha
///////////////////
% Test
Ap3 =;
; 21; 35;];
Map1 = [82,7; 91,38; 83,46; 71,44; 64,60; 68,58; 83,69; 87,76; 74,78; 71,71];
MAP2 =;
;];
Maxiter = 100;
Sizescale = 1000;
Changerate = 0.05;
[Time, opt, fval] = tspga (map1, maxiter, sizescale, changerate)
////////////////////////
Function [time, opt, fval] = tspga (MAP, maxiter, sizescale, changerate)
% This is Function
% Input:
% Output:
T = cputime;
% Maxiter = 100;
% Sizescale = 100;
N = max (SIZE (MAP ));
% Compute the roadmatrix
Distmatrix = zeros (N, N );
For I = 1: N
For j = 1: N
Distmatrix (I, j) = distance (MAP (I, :), map (J ,:));
End
End
% To inner the road (oder the CITES)
Road = ones (sizescale, N );
For I = 1: sizescale
Road (I, :) = randperm (N );
End
%
Dist = zeros (sizescale, 1 );
For I = 1: sizescale
For j = 1 :( N-1)
Dist (I) = dist (I) + distmatrix (Road (I, j), road (I, j + 1 ));
End
End
[Minroad, ii] = min (DIST );
For iter = 1: maxiter
Flag = 0;
% Sumdist = sum (DIST );
Minroad = min (DIST );
Maxroad = max (DIST );
For I = 1: sizescale
Fit = fitness (minroad, maxroad, dist (I ));
If fit = 1
Flag = Flag + 1;
% Get new road
Road (I, :) = road (II ,:);
Changelocation = randint (1, 2, [1 N]);
If changelocation (1) = changelocation (2)
Continue;
End
Temp = road (I, changelocation (1 ));
Road (I, changelocation (1) = road (I, changelocation (2 ));
Road (I, changelocation (2) = temp;
Dist (I) = 0;
For j = 1 :( N-1)
Dist (I) = dist (I) + distmatrix (Road (I, j), road (I, j + 1 ));
End
End
End
% Change
% Bianyi
Numchange = int16 (changerate * sizescale );
Idchange = randint (1, numchange, [1, sizescale]);
Step = 3;
For I = 1: numchange
If idchange (I) = II
Continue;
End
L = 1;
While (L + step) <n
Temp = road (idchange (I), L );
Road (idchange (I), L) = road (idchange (I), L + step );
Road (idchange (I), L + step) = temp;
L = L + step;
End
Dist (I) = 0;
For j = 1 :( N-1)
Dist (I) = dist (I) + distmatrix (Road (I, j), road (I, j + 1 ));
End
End
[Minroad, ii] = min (DIST );
% Disp ('this iter the OPT is ');
% Road (II ,:)
% Minroad
Flag
% Dist
End
Plot (MAP (:, 1), map (:, 2 ),'*');
Hold on
Xx = map (Road (II, :), 1 );
Xx = [xx; Map (Road (II, 1), 1)];
YY = map (Road (II, :), 2 );
YY = [yy; Map (Road (II, 1), 2)];
Plot (XX, YY );
Time = cputime-T;
Opt = road (II ,:);
Fval = minroad;
Function d = distance (A, B)
% This function to get the distance of two point a, B
D = SQRT (A (1)-B (1) ^ 2 + (A (2)-B (2) ^ 2 );
Function f = fitness (Fmin, FMAX, froad)
% This function to computer the fitness this road
% This the F is 0 or 1 froad more less the f more posible 1
T = (froad-fmin)/(fmax-fmin );
F = Rand <(1-t ));