clc;clear all;
load china; % geographic information
plotcities(province, border, city); % draw the map of China
numberofcities = length(city); % number of cities
% distance matrix: dis(i,j) is the distance between city i and j.
dis = distancematrix(city);
alpha = 1 %启发因子,信息素的重要程度
beta = 2 %期望因子,城市间距离的重要程度
rou = 0.5 %信息素残留参数
Q = 2000 %%信息素增强系数
m = numberofcities; %m 蚂蚁数量
Eta = 1./dis;
Tau = ones(numberofcities,numberofcities);
Tauroute = zeros(m,numberofcities);
NC_max = 100;
R_best=zeros(NC_max,numberofcities);
L_best=inf.*ones(NC_max,1);
NC = 1;
while NC < NC_max
Randpos = [];
for i = 1:(ceil(m/numberofcities))
Randpos = [Randpos,randperm(numberofcities)];
end
Tauroute(:,1) = (Randpos(1,1:m))';
for j = 2:numberofcities
for i = 1:m
visited = Tauroute(i,1:(j-1));
visting = zeros(1,(numberofcities-j+1));
prob = visting;
Jc = 1;
for k = 1:numberofcities
if isempty(find(visited==k,1))
visting(Jc) = k;
Jc = Jc + 1;
end
end
for k = 1:length(visting)
prob(k) = (Tau(visited(end),visting(k))^alpha)*(Eta(visited(end),visting(k))^beta);
end
prob = prob/(sum(prob));
pcum = cumsum(prob);
Select = find(pcum>=rand);
tovisit = visting(Select(1));
Tauroute(i,j) = tovisit;
end
end
if NC > 2
Tauroute(1,:) = R_best(NC-1,:);
end
L = zeros(m,1);
for i = 1:m
R = Tauroute(i,:);
L(i) = totaldistance(R, dis);
end
L_best(NC) = min(L);
pos = find(L==L_best(NC));
R_best(NC,:) = Tauroute(pos(1),:);
Rbest = Tauroute(pos(1),:);
plotroute(city, Rbest, L_best(NC), NC);
NC = NC + 1;
Delta_Tau = zeros(numberofcities,numberofcities);
for i = 1:m
for j = 1:(numberofcities-1)
Delta_Tau(Tauroute(i,j),Tauroute(i,j+1)) = Delta_Tau(Tauroute(i,j),Tauroute(i,j+1))+Q/L(i);
end
Delta_Tau(Tauroute(i,numberofcities),Tauroute(i,1))=Delta_Tau(Tauroute(i,numberofcities),Tauroute(i,1))+Q/L(i);
end
Tau = (1-rou).*Tau + Delta_Tau;
Tauroute = zeros(m,numberofcities);
end
POS = find(L_best == min(L_best));
SR = R_best(POS(1),:);
SL = L_best(POS(1));
plotroute(city, SR, SL, NC);