%螞蟻算法test
%用產生的一個圓上的十個點來檢驗螞蟻算法
clc
clear
%參數
alpha = 1 ; %信息素指數
beta = 5 ; %啓發指數
rho = 0.5 ; %揮發係數
n = 16 ; %城市個數
k = 20 ; %迭代次數
m = n - 1 ; %螞蟻只數,這裏取比城市數目少一的螞蟻只數
Q = 100 ;
bestr = inf ;
%產生一個圓上的十個點
x = zeros(1,n) ;
y = x ;
for i = 1 : (n/2)
x(i) = rand * 20 ;
y(i) = sqrt(100 - (x(i) - 10) ^ 2) + 10;
end
for i = (n/2 + 1) : n
x(i) = rand * 20 ;
y(i) = - sqrt(100 - (x(i) - 10) ^ 2) + 10;
end
plot(x,y,'.') ;
%計算距離
d = zeros(n,n) ;
for i = 1 : n
for j = 1 : n
d(i,j) = sqrt( ( x(i) - x(j) ) ^ 2 + ( y(i) - y(j) ) ^ 2) ;
end
end
temp = min(d) ;
dmin = temp(1) ;
tau = ones(n,n) ;
%tau = tau ./ (n * dmin) ; %初始化tau信息素矩陣
%開始迭代
for i = 1 : k
%初始化
visited = zeros(m,n) ; %用visited 來儲存全部螞蟻走過的城市 m×n 其中未到達的城市爲0
visited(:,1) = (randperm(n,m))'; %將m只螞蟻隨機放在n座城市 即產生一列1到n的隨機數進行第一列數據的更新
for b = 2 : n %全部螞蟻都走到第b個城市時
current = visited(:,(b-1)) ; %全部螞蟻如今所在城市 m×1
allow = zeros(m,(n - b + 1)) ;
for a = 1 : m
j = 1 ;
for s = 1 : n
if length(find(visited(a,:) == s)) == 0
allow(a,j) = s ;
j = j + 1 ;
end
end
end
l = n-b+1 ;
for a = 1 : m %分析第a只螞蟻
p = zeros(1,l) ;
for j = 1 : l %根據下式來選擇下一個城市
p(j) = ( ( tau( current(a,1) , allow(a,j) ) ) ^ alpha ) * ( ( 1 / d( current(a,1) , allow(a,j) ) ) ^ beta ) ;
end
p = p ./ sum(p) ; %採用輪盤賭的方式
p = cumsum(p) ;
pick = rand ;
for c = 1 : l
if pick < p(c)
visited(a,b) = allow(a,c) ; %找到符合要求的城市 並 記入螞蟻a的路徑中
break ;
end
end
end
end
%計算每隻螞蟻所走的路徑總長
L = zeros(1,m) ;
for a = 1 : m
t = d(visited(a,n),visited(a,1)) ;
for b = 1 : (n - 1)
t = t + d(visited(a,b),visited(a,(b + 1)));
end
L(a) = t ;
end
[newbestr,newbestant] = min(L) ; %尋本次迭代最短路徑及其相應螞蟻
if newbestr < bestr %到目前爲止最優值的保存
bestr = newbestr ;
bestroad = visited(newbestant,:) ;
end
%離線更新信息素矩陣
%揮發
for a = 1 : m
tau(visited(a,n),visited(a,1)) = tau(visited(a,n),visited(a,1)) * (1 - rho) ;
for b = 1 : (n - 1)
tau(visited(a,b),visited(a,(b + 1))) = tau(visited(a,b),visited(a,(b + 1))) * (1 - rho) ;
end
end
%增強
tau(visited(newbestant,n),visited(newbestant,1)) = tau(visited(newbestant,n),visited(newbestant,1)) + Q / L(newbestant) ;
for b = 1 : (n - 1)
tau(visited(newbestant,b),visited(newbestant,(b + 1))) = tau(visited(newbestant,b),visited(newbestant,(b + 1))) + Q / L(newbestant) ;
end
end
bestr
bestx = zeros(1,n) ;
besty = zeros(1,n) ;
for i = 1 : n
bestx(i) = x(bestroad(i)) ;
besty(i) = y(bestroad(i)) ;
end
bestx = [bestx,bestx(1)] ;
besty = [besty,besty(1)] ;
plot(bestx,besty,'-') ;