[plain]viewplaincopy1.functionDE(Gm,F0)2.3.t0=cputime;4.%差分进化算法程序5.%F0是变异率%Gm最大迭代次数6.Gm=10000;7.F0=0.5;8.Np=100;9.CR=0.9;%交叉概率10.G=1;%初始化代数11.D=10;%所求问题的维数12.Gmin=zeros(1,Gm);%各代的最优值13.best_x=zeros(Gm,D);%各代的最优解14.value=zeros(1,Np);15.16.%产生初始种群17.%xmin=-10;xmax=100;%带负数的下界18.xmin=-5.12;19.xmax=5.12;20.functiony=f(v)21.%Rastrigr函数22.y=sum(v.^2-10.*cos(2.*pi.*v)+10);23.end24.25.X0=(xmax-xmin)*rand(Np,D)+xmin;%产生Np个D维向量26.XG=X0;27.28.%%%%%%%%%%%%%----这里未做评价,不判断终止条件----%%%%%%%%%%%%%%%%%%%%%%%%29.30.XG_next_1=zeros(Np,D);%初始化31.XG_next_2=zeros(Np,D);32.XG_next=zeros(Np,D);33.34.whileG=Gm35.G36.%%%%%%%%%%%%%%%%%%%%%%%%----变异操作----%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%37.fori=1:Np38.%产生j,k,p三个不同的数39.a=1;40.b=Np;41.dx=randperm(b-a+1)+a-1;42.j=dx(1);43.k=dx(2);44.p=dx(3);45.%要保证与i不同46.ifj==i47.j=dx(4);48.elseifk==i49.k=dx(4);50.elseifp==i51.p=dx(4);52.end53.end54.end55.56.%变异算子57.suanzi=exp(1-Gm/(Gm+1-G));58.F=F0*2.^suanzi;59.%变异的个体来自三个随机父代60.61.son=XG(p,:)+F*(XG(j,:)-XG(k,:));62.forj=1:D63.ifson(1,j)xmin&son(1,j)xmax%防止变异超出边界64.XG_next_1(i,j)=son(1,j);65.else66.XG_next_1(i,j)=(xmax-xmin)*rand(1)+xmin;67.end68.end69.end70.%%%%%%%%%%%%%%%%%%%%%%%---交叉操作----%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%71.72.73.fori=1:Np74.randx=randperm(D);%[1,2,3,...D]的随机序列75.forj=1:D76.77.ifrandCR&randx(1)~=j%CR=0.978.XG_next_2(i,j)=XG(i,j);79.else80.XG_next_2(i,j)=XG_next_1(i,j);81.end82.end83.end84.85.%%%%%%%%%%%%%%%%%%----选择操作---%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%86.fori=1:Np87.iff(XG_next_2(i,:))f(XG(i,:))88.89.XG_next(i,:)=XG_next_2(i,:);90.else91.XG_next(i,:)=XG(i,:);92.end93.end94.95.%找出最小值96.fori=1:Np97.value(i)=f(XG_next(i,:));98.end99.[value_min,pos_min]=min(value);100.101.%第G代中的目标函数的最小值102.Gmin(G)=value_min;103.%保存最优的个体104.best_x(G,:)=XG_next(pos_min,:);105.106.XG=XG_next;107.trace(G,1)=G;108.trace(G,2)=value_min;109.G=G+1;110.111.end112.[value_min,pos_min]=min(Gmin);113.best_value=value_min114.best_vector=best_x(pos_min,:)115.fprintf('DE所耗的时间为:%f\n',cputime-t0);116.%画出代数跟最优函数值之间的关系图117.plot(trace(:,1),trace(:,2));118.119.end