实数编码的遗传算法与MATLAB
(一)函数示例
Z=x.^2-10*cos(2*pi*x)+10+y.^2-10*cos(2*pi*y)+10
(二)MATLAB的实现
1)GAss(主函数)
clc
clear
x=-5.12:0.01:5.12;
y=-5.12:0.01:5.12;
[X,Y]=meshgrid(x,y);
Z=X.^2-10*cos(2*pi*X)+10+Y.^2-10*cos(2*pi*Y)+10;
mesh(X,Y,Z)
%%%%%%%%%%%%%%%初始化种群%%%%%%%%%%%
N=50;dim=2;B=5.12;Pc=0.75;pm=0.3
Po=-B+rand(N,2)*2*B;
%%%%%%%%%%%%函数评价%%%%%%%%%%%%%%%
for it=1:10
for i=1:N
fit(i)=GAmb(Po(i,1),Po(i,2));
end
[ymax,ind1]=max(fit);
figure(1)
set(gca,'nextplot','replace');
mesh(X,Y,Z)
hold on
plot3(Po(:,1),Po(:,2),fit,'b*')
plot3(Po(ind1,1),Po(ind1,2),fit(ind1),'mo')
%%%%%%%%%%%%%%选择%%%%%%%%%%%%%%%
p=fit/sum(fit); %%计算比例概率
Lp(1)=fit(1);
for i=2:N
Lp(i)=Lp(i-1)+fit(i); %%计算累积概率
end
for i=1:N
ind=find((Lp-rand)>0); %%找出轮盘赌选择的指标
Co(i)=ind(1);
nPo(i,:)=Po(ind(1),:); %%将对应指标的染色体取出来赋值给新的种群
end
%%%%%%%%%%%%%%交叉%%%%%%%%%%%%%%%%%%
for i=1:2:N
[x1,y1]=GAjc(nPo(i,:),nPo(i+1,:),Pc);
Nnpo(i,:)=x1;
Nnpo(i+1,:)=y1;
end
%%%%%%%%%%%%%%变异%%%
for i=1:N
Npo(i,:)=GAby(Nnpo(i,:),pm);
end
%%%%%%%%%%%%%%%%%%%%%
%保留最好的个体
Npo(1,:)=Po(ind1,:);
Npo(41:N,:)=-B+rand(10,2)*2*B;%%避免早熟
%%新的种群要赋值给原来的变量
Po=Npo;
end
2)GAmb(目标函数)
function z1=GAmb(x1,y1)
z1=x1^2-10*cos(2*pi*x1)+10+y1^2-10*cos(2*pi*y1)+10;
3)GAjc(交叉函数)
function [x1,y1]=GAjc(x,y,Pc)
if rand<Pc
lameda1=0.4;
x1=lameda1*x+(1-lameda1)*y;
y1=lameda1*y+(1-lameda1)*x;
else
x1=x;
y1=y;
end
4)GAby(变异函数)
function x=GAby(x,pm)
if rand<pm
x=x+[(1-2*rand)*10e-3 (1-2*rand)*10e-3 ];
end
5)结果图例
来源:CSDN
作者:不要你觉得
链接:https://blog.csdn.net/qq_43202087/article/details/104760407