|
发表于 2022-11-15 13:11:50
|
显示全部楼层
%%清空环境变量
clear all
clc
load citys_data.mat
citys=xlsread('citys31.xlsx','B2:C32');
%%计算城市间相互距离
n=size(citys,1);
D=zeros(n,n);
for i=1:n
for j=1:n
if i~=j
D(i,j)=sqrt(sum(citys(i,:)-citys(j,:)).^2);
else
D(i,j)=1e-4;
end
end
end
%%初始化参数
m=100;
alpha=1;
bata=5;
rho=0.2;
Q=10;
Eta=1./D;
Tau=ones(n,n);
Table=zeros(m,n);
iter=1;
iter_max=200;
Route_best=zeros(iter_max,n);
Length_best=zeros(iter_max,1);
Length_ave=zeros(iter_max,1);
%%迭代寻找最佳路径
while iter<=iter_max
%随机产生各个蚂蚁的起点城市
start=zeros(m,1);
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(i,1:(j-1));
allow_index=~ismember(citys_index,tabu);
allow=citys_index(allow_index);
P=allow;
for k=1:length(allow)
P(k) = Tau(tabu(end),allow(k))^alpha * Eta(tabu(end),allow(k))^beta;
end
P=P/sum(P);
Pc=cumsum(P);
target_index=find(Pc>=rand);
target=allow(target_index(1));
Table(i,j)=target;
end
end
Length=zeros(m,1);
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
if iter==1
[min_Length,min_index]=min(Length);
Length_best(iter)=min_Length;
Length_ave(iter)=mean(Length);
Route_best(iter,:)=Table(min_index,:);
else
[min_Length,min_index]=min(Length);
Length_best(iter)=min(Length_best(iter-1),min_Length);
Length_ave(iter)=mean(Length);
if Length_best(iter)==min_Length
Route_best(iter,:)=Table(min_index,:);
else
Route_best(iter,:)= Route_best((iter-1),:);
end
end
Delta_Tau=zeros(n,n);
for i =1:m
for j=1:(n-1)
Delta_Tau(Table(i,j),Table(i,j+1))=Delta_Tau(Table_(i,j),Table(i,j+1))+Q/Length(i);
end
Delta_Tau(Table(i,n),Table(i,1))=Delta_Tau(Table(i,n),Table(i,1))+Q/Length(i);
end
Tau=(1-rho)*Tau+Delta_Tau;
iter=iter+1;
Table=zeros(m.n);
end
%%结果显示
[Shortest_Length,index]=min(Length_best);
Shortest_Route=Route_best(index,:);
disp(['最短距离:' num2str(Shortest_Length)]);
disp(['最短路径:' num2str( [Shortest_Route Shortest_Route(1)] )]);
disp(['收敛迭代次数:' num2str(Limit_iter)]);
disp(['程序执行时间:' num2str(Time_Cost),'秒']);
以上是代码 |
|