雷英杰编著的《MATLAB遗传算法工具箱及应用》第七章的第一个例子

来源:百度知道 编辑:UC知道 时间:2024/06/02 14:01:35
figure(1);
fplot('variable.*sin(10*pi*variable)+2.0',[-2,2]);
nind=40;
maxgen=10;
preci=10;
ggap=0.9;
trace=zeros(2,maxgen);
fieldd=[20;-1;2;1;0;1;1];
chrom=crtbp(nind, preci);
gen=0;
variable=bs2rv(chrom,fieldd);
objv=variable.*sin(10*pi*variable)+2.0;
while gen<maxgen,
fitnv=ranking(-objv);
selch=select('sus',chrom,fitnv,ggap);
selch=recombin('xovsp',selch,0.7);
selch=mut(selch);
variable=bs2rv(selch,fieldd);
objvsel=variable.*sin(10*pi*variable)+2.0;
[chrom objv]=reins(chrom,selch,1,1,objv,objvsel);
gen=gen+1;
[y,i]=max(objv),hold on;
plot(variable(i),y,'bo');
trace(1,gen)=max(objv);
trace(2,gen)=sum(objv)/length(objv);
end
variable=bs2rv(chrom,fieldd);
hold on,grid;
plot(variable,'objv','b*');
figure(2);
plot(trace(1,:)');
hold

程序倒数第六行应该是variable',还有注释掉倒数12行。把hold on的分号都去掉。
figure(1);
fplot('variable.*sin(10*pi*variable)+2.0',[-1,2]);
nind=40;
maxgen=25;
preci=20;
ggap=0.9;
trace=zeros(2,maxgen);
fieldd=[20;-1;2;1;0;1;1];
chrom=crtbp(nind, preci);
gen=0;
variable=bs2rv(chrom,fieldd);
objv=variable.*sin(10*pi*variable)+2.0
while gen<maxgen
fitnv=ranking(-objv);
selch=select('sus',chrom,fitnv,ggap);
selch=recombin('xovsp',selch,0.7);
selch=mut(selch);
variable=bs2rv(selch,fieldd);
objvsel=variable.*sin(10*pi*variable)+2.0;
[chrom objv]=reins(chrom,selch,1,1,objv,objvsel);
gen=gen+1;
[y,i]=max(objv);
hold on;
%plot(variable(i),y,'bo')
trace(1,gen)=max(objv);
trace(2,gen)=sum(objv)/length(objv);
end
variable=bs2rv(chrom,fieldd);
hold on
grid;
plot(variable',objv','b*');
figur