%% 更新每一个粒子的位置 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); 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(i)>dist
individual(i,:)=xnew1(i,:); end
% 全体最优值更新速度
c1=round(rand*(n-2))+1; c2=round(rand*(n-2))+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=tourGbest(chb1:chb2); ncros=size(cros,2); 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(i)>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 indiFit(i)>dist
individual(i,:)=xnew1(i,:); end
end
[value,index]=min(indiFit); L_best(N)=indiFit(index); tourGbest=individual(index,:); end
%% 其他函数
function dist=dist(x,D) n=size(x,2); dist=0; for i=1:n-1
dist=dist+D(x(i),x(i+1)); end
dist=dist+D(x(1),x(n));
function indiFit=fitness(x,cityCoor,cityDist) m=size(x,1); n=size(cityCoor,1); indiFit=zeros(m,1); for i=1:m for j=1:n-1
indiFit(i)=indiFit(i)+cityDist(x(i,j),x(i,j+1)); end
indiFit(i)=indiFit(i)+cityDist(x(i,1),x(i,n)); end