%%
nMax=100; %进化次数
indiNumber=100; %个体数目
n=10; %粒子坐标
for i=1:indiNumber
individual(i,:)=randperm(n); %粒子位置,randperm(n)是1到n随机置换构造的行向量
end
%%计算种群适应度
indiFit=fitness(individual,cityCoor,cityDist);
[value,index]=min(indiFit);
tourPbest=individual; %当前个体最优
tourGbest=individual(index,:); %当前全局最优
recordPbest=inf*ones(1,indiNumber); %个体最优记录(最优适应度值)
recordGbest=indiFit(index); %群体最优记录(最优适应度值)
for h=1:nMax
%%交叉操作
for i=1:indiNumber
%产生交叉位
c1=unidrnd(n-1);
c2=unidrnd(n-1);
while c1==c2 %如果两个交叉位不幸相同,则重新随机选取交叉位
c1=round(rand*(n-2))+1;
c2=round(rand*(n-2))+1;
end
chb1=min(c1,c2); %起始交叉位
chb2=max(c1,c2); %结束第二交叉位
cros=tourPbest(i,chb1:chb2); %交叉区域矩阵
ncros=size(cros,2);
xnew1(i,:)=tourPbest(i,:);
for j=1:ncros
for k=1:n
if xnew1(i,k)==cros(j)
xnew1(i,k)=0;
for t=1:n-k
temp=xnew1(i,k+t-1);
xnew1(i,k+t-1)=xnew1(i,k+t);
xnew1(i,k+t)=temp;
end
end
end
end
%插入交叉区域
xnew1(i,n-ncros+1:n)=cros;
%新路径长度短则接受
dist=0;
for j=1:n-1
dist=dist+cityDist(xnew1(i,j),xnew1(i,j+1));
end
dist=dist+cityDist(xnew1(i,1),xnew1(i,n));
if indiFit>dist
individual(i,:)=xnew1(i,:);
end
%%变异操作
c1=round(rand*(n-1))+1;
c2=round(rand*(n-1))+1;
while c1==c2
c1=round(rand*(n-2))+1;
c2=round(rand*(n-2))+1;
end
%交换变异位
temp=xnew1(i,c1);
xnew1(i,c1)=xnew1(i,c2);
xnew1(i,c2)=temp;
%新路径长度短则接受
dist=0;
for j=1:n-1
dist=dist+cityDist(xnew1(i,j),xnew1(i,j+1));
end
dist=dist+cityDist(xnew1(i,1),xnew1(i,n));
if dist<indiFit(i)
individual(i,:)=xnew1(i,:);
end
end
%%重新计算最优适应度值
indiFit=fitness(individual,cityCoor,cityDist);
[value,index]=min(indiFit);
tourPbest=individual; %当前个体最优
tourGbest=individual(index,:); %当前全局最优
recordPbest=indiFit; %个体最优记录(最优适应度值)
recordGbest=indiFit(index); %群体最优记录(最优适应度值)
result1(h,:)=recordGbest; %记录每次迭代最优适应度
result2(h,:)=tourGbest; %记录每次迭代最优方案,用于后续解码
end
subplot(3,1,1);
plot(result1);
title('适应度值变化曲线');
subplot(3,1,2);
plot(cityCoor(:,1),cityCoor(:,2),'p');
grid;
line(cityCoor(result2(nMax,:),1),cityCoor(result2(nMax,:),2));
subplot(3,1,3);
plot(cityCoor(:,1),cityCoor(:,2),'p');
grid;
评论0
最新资源