資源簡(jiǎn)介
解決TSP問題的蟻群算法MATLAB代碼,自己編寫,實(shí)測(cè)好用!
代碼片段和文件信息
function?[?shortest_Routeshortest_Length?]?=?AntColony(?citys?)
n=size(citys1);
D=zeros(nn);
for?i=1:n
????for?j=1:n
????????if?i~=j
????????????D(ij)=sqrt(sum((citys(i:)-citys(j:)).^2));
????????else
????????????D(ij)=1e-4;
????????end
????end
end
m=35;
alpha=1;
beta=5;
rho=0.1;
Q=1;
Eta=1./D;
Tau=ones(nn);
Table=zeros(mn);
iter=1;iter_max=200;
Route_best=zeros(iter_maxn);
Length_best=zeros(iter_max1);
Leangth_ave=zeros(iter_max1);
while?iter<=iter_max
????start=zeros(m1);
????
????for?i=1:m
????????temp=randperm(n);
????????start(i)=temp(1);
????end
????
????Table(:1)=start;
????
????citys_index=1:n;
????
????for?i=1:m
????????for?j=2:n
????????????tabu=Table(i1:(j-1));
????????????
????????????allow_index=~ismember(citys_indextabu);
????????????allow=citys_index(allow_index);
????????????
????????????P=allow;
????????????
????????????%計(jì)算城市間轉(zhuǎn)移概率
????????????for?k?=1:length(allow)
????????????????P(k)=Tau(tabu(end)allow(k))^alpha?*?Eta(tabu(end)allow(k))^beta;
????????????end
????????????P=P/sum(P);
????????????
????????????%運(yùn)用輪盤賭法選擇下一個(gè)訪問城市
????????????Pc=cumsum(P);
????????????target_index=find(Pc>=rand);
????????????target=allow(target_index(1));
????????????Table(ij)=target;
????????end
????end
????
????%計(jì)算各個(gè)螞蟻的路徑距離
????Length=zeros(m1);
????for?i?=?1:m
????????Route=Table(i:);
????????for?j?=1:(n-1)
????????????Length(i)=Length(i)+D(Route(j)Route(j+1));
????????end
????????Length(i)=Length(i)+D(Route(n)Route(1));
????end
????
評(píng)論
共有 條評(píng)論