二元函数为y=x1^2+x2^2,x∈[-5,5]
NIND=121; %初始种群的个数(Number of individuals)
NVAR=2; %一个染色体(个体)有多少基因
PRECI=20; %变量的二进制位数(Precision of variables)
MAXGEN=200; %最大遗传代数(Maximum number of generations)
GGAP=0.8; %代沟(Generation gap),以一定概率选择父代遗传到下一代
trace=zeros(MAXGEN,2); %寻优结果的初始值
Chrom=crtbp(NIND,PRECI*NVAR); %初始种群
%区域描述器(Build field descriptor)
%确定每个变量的二进制位数,取值范围,及取值范围是否包括边界等。
FieldD=[rep([PRECI],[1,NVAR]);rep([-5;5],[1,NVAR]);rep([1;0;1;1],[1,NVAR])];
Objv=objfun(bs2rv(Chrom,FieldD))
gen=1; %代计数器
while gen<=MAXGEN
Fitv=ranking(Objv); %分配适应度值(Assign fitness values)
SelCh=select('sus',Chrom,Fitv,GGAP); %选择
SelCh=recombin('xovsp',SelCh,1); %重组
SelCh=mut(SelCh); %变异
ObjVSel=objfun(bs2rv(SelCh,FieldD));%子代个体的十进制转换
%重插入子代的新种群
[Chrom,Objv]=reins(Chrom,SelCh,1,1,Objv,ObjVSel);
trace(gen,1)=min(Objv); %遗传算法性能跟踪
trace(gen,2)=sum(Objv)/length(Objv);
gen=gen+1; %代计数器增加
end
plot(trace(:,1));
hold on
plot(trace(:,2),'.')
grid
legend('最优解的变化','解的平均值的变化')
根据上面的求解模型,可以写出模型的.M文件如下,即适应度函数
% OBJFUN.M
% Syntax: ObjVal = objfun1(Chrom,rtn_type)
%
% Input parameters:
% Chrom - Matrix containing