资源描述:
《MPST问题MATLAB程序》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、基于遗传算法的TSP算法matlab代码主程序:clc;clearall;closeall;globalxyx=[03154037910141714121019261115722212715152021242528];y=[025478119620369129161817121450919141713201618];a=[88.265.534.57.22.31.46.54.112.75.83.83.43.55.87.57.84.66.26.82.47.69.6101268.14.2];h=0:3
2、0;t=31+1;%送货点数s=1500;%初始中群数G=500;%最大迭代次数c=25;%一次选取25个样本pc=0.80;%交配率pm=0.01;%变异率pop=zeros(s,t);fori=1:spop(i,1:t-1)=randperm(t-1);%初始化种群endfork=1:1:G%GA开始¼ifmod(k,50)==1kendpop=distance1(pop);%调用距离函数pop=select(pop,c);%调用选择函数p1=rand;ifp1>=pcpop=cross(p
3、op);%调用交配函数endp2=rand;ifp2>=pmpop=mutate(pop);%调用变异函数endend%GA结束%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%bestL=min(pop(:,t))J=pop(:,t);fi=1./J;[Oderfi,Indexfi]=sort(fi);%对fi进行排序BestS=pop(Indexfi(s),:);%得到最短路径I=B
4、estS;fori=1:1:t-1x1(i)=x(I(i));y1(i)=y(I(i));endx1(t)=x(I(1));y1(t)=y(I(1));cities_new=[x1;y1];disp('BestRouteis:');disp(cities_new);pos=[cities_newcities_new(:,1)];lentemp=0;fori=1:1:t-1temp=(abs(pos(1,i)-pos(1,i+1))+abs(pos(2,i)-pos(2,i+1)));lentem
5、p=lentemp+temp;enddisp('ShortestLengthis:');disp(lentemp);plot(x1,y1,'-or');xlabel('Xaxis'),ylabel('Yaxis'),title('最短路径');axis([0,1,0,1]);axis([0,30,0,20]);axison距离函数matlab代码:function[pop]=distance1(pop)globalxy[s,t]=size(pop);fori=1:1:sdd=0;pos=pop(
6、i,1:t-1);pos=[pospos(:,1)];forj=1:1:t-1m=pos(j);n=pos(j+1);dd=dd+(abs(x(m)-x(n))+abs(y(m)-y(n)));endpop(i,t)=dd;end选择函数matlab代码:function[pop]=select(pop,c)[s,t]=size(pop);m11=(pop(:,t));m11=m11';mmax=zeros(1,c);mmin=zeros(1,c);num=1;whilenum7、的C个样本[a,mmax(num)]=max(m11);m11(mmax(num))=0;num=num+1;endnum=1;whilenum8、erm(s);%将种群随机排序fori=1:2:s%随机选择两个交叉点m=randperm(t-3)+1;crosspoint(1)=min(m(1),m(2));crosspoint(2)=max(m(1),m(2));%任意两行交叉x1=n(i);x2=n(i+1);%将X1左边与X2的左边互换middle=pop(x1,1:crosspoint(1));pop(x1,1:crosspoint(1))=pop(x2,1:crosspoint(1));pop(x2,1:crosspoint(1