clc,clear sj=load(‘data3.txt‘) %加载敌方100 个目标的数据 x=sj(:,1); y=sj(:,2); d1=[70,40]; sj0=[d1;sj;d1]; %增加一个点[70,40]作为首尾 sj=sj0; d=zeros(102); %距离矩阵d % 通过向量化的方法计算距离矩阵 amount = size(sj,1); dist_matrix = zeros(amount, amount); coor_x_tmp1 = sj(:,1) * ones(1,amount); coor_x_tmp2 = coor_x_tmp1‘; coor_y_tmp1 = sj(:,2) * ones(1,amount); coor_y_tmp2 = coor_y_tmp1‘; dist_matrix = sqrt((coor_x_tmp1-coor_x_tmp2).^2 + (coor_y_tmp1-coor_y_tmp2).^2); %存储各个城市之间距离的矩阵 d=dist_matrix; %设置参数 L=102; w=50; dai=100; %通过改良圈算法选取优良父代A for k=1:w c=randperm(100); %把1到100这些数随机打乱得到的一个数字序列 c1=[1,c+1,102]; %头尾增加1,102 flag=1; %设置标志 while flag>0 flag=0; for m=1:L-3 for n=m+2:L-1 if d(c1(m),c1(n))+d(c1(m+1),c1(n+1))<d(c1(m),c1(m+1))+d(c1(n),c1(n+1)) flag=1; c1(m+1:n)=c1(n:-1:m+1); end end end end J(k,c1)=1:102; %产生了w个(50个)父代A end J=J/102; J(:,1)=0; J(:,102)=1; %头尾分别为0,1,中间元素介于它们之间 rand(‘state‘,sum(clock)); %遗传算法实现过程 A=J; for k=1:dai %产生0~1 间随机数列进行编码 dai=100 B=A; c=randperm(w); %1.交配产生子代B for i=1:2:w F=2+floor(100*rand(1)); temp=B(c(i),F:102); %两两配对 B(c(i),F:102)=B(c(i+1),F:102); B(c(i+1),F:102)=temp; end %2.变异产生子代C by=find(rand(1,w)<0.1); if length(by)==0 by=floor(w*rand(1))+1; end C=A(by,:); L3=length(by); for j=1:L3 bw=2+floor(100*rand(1,3)); bw=sort(bw); C(j,:)=C(j,[1:bw(1)-1,bw(2)+1:bw(3),bw(1):bw(2),bw(3)+1:102]); end %3.在父代和子代中选择优良品种作为新的父代 G=[A;B;C]; G=[A;B;C]; TL=size(G,1); [dd,IX]=sort(G,2);temp(1:TL)=0; for j=1:TL for i=1:101 temp(j)=temp(j)+d(IX(j,i),IX(j,i+1)); end end [DZ,IZ]=sort(temp); %从小到大 A=G(IZ(1:w),:); %选择优良的50个 end path=IX(IZ(1),:) long=DZ(1) xx=sj0(path,1);yy=sj0(path,2); plot(xx,yy,‘-o‘)
时间: 2024-10-06 23:34:01