?? ga.m
字號:
%用遺傳算法進行簡單函數的優化,可以顯示中間過程
clear
bn=22; %個體串長度
inn=50; %初始種群大小
gnmax=200; %最大代數
pc=0.8; %交叉概率
pm=0.05; %變異概率
%產生初始種群
s=round(rand(inn,bn));
gnf1=5;
gnf2=20;
%計算適應度,返回適應度f和累積概率p
[f,p]=objf(s);
gn=1;
while gn<gnmax+1
xp=-1:0.01:2;
yp=ft(xp);
for d=1:inn
xi=n2to10(s(d,:));
xdi(d)=-1.0+xi*3/(power(2,bn)-1);
end
yi=ft(xdi);
plot(xp,yp,'b-',xdi,yi,'g*');
strt=['當前代數 gn=' num2str(gn)];
text(-0.75,1,strt);
text(-0.75,3.5,'* 當前種群','Color','g');
if gn<gnf1
pause;
end
hold on;
for j=1:2:inn
%選擇操作
seln=sel(s,p);
xs1=n2to10(s(seln(1),:));
xds1=-1.0+xs1*3/(power(2,bn)-1);
ys1=ft(xds1);
xs2=n2to10(s(seln(2),:));
xds2=-1.0+xs2*3/(power(2,bn)-1);
ys2=ft(xds2);
hold on;
drawnow;
plot(xds1,ys1,'r*',xds2,ys2,'r*');
%交叉操作
scro=cro(s,seln,pc);
scnew(j,:)=scro(1,:);
scnew(j+1,:)=scro(2,:);
%變異操作
smnew(j,:)=mut(scnew(j,:),pm);
smnew(j+1,:)=mut(scnew(j+1,:),pm);
end
drawnow;
text(-0.75,3.3,'* 選擇后','Color','r');
if gn<gnf1
pause;
end
for d=1:inn
xc=n2to10(scnew(d,:));
xdc(d)=-1.0+xc*3/(power(2,bn)-1);
end
yc=ft(xdc);
drawnow;
plot(xdc,yc,'m*');
text(-0.75,3.1,'* 交叉后','Color','m');
if gn<gnf1
pause;
end
hold on;
for d=1:inn
xm=n2to10(smnew(d,:));
xdm(d)=-1.0+xm*3/(power(2,bn)-1);
end
ym=ft(xdm);
drawnow;
plot(xdm,ym,'c*');
text(-0.75,2.9,'* 變異后','Color','c');
if gn<gnf2
pause;
end
hold off;
s=smnew; %產生了新的種群
%計算新種群的適應度
[f,p]=objf(s);
%記錄當前代最好和平均的適應度
[fmax,nmax]=max(f);
fmean=mean(f);
ymax(gn)=fmax;
ymean(gn)=fmean;
%記錄當前代的最佳個體
x=n2to10(s(nmax,:));
xx=-1.0+x*3/(power(2,bn)-1);
xmax(gn)=xx;
gn=gn+1;
end
gn=gn-1;
figure(2);
subplot(2,1,1);
plot(1:gn,[ymax;ymean]);
title('歷代適應度變化','fonts',10);
legend('最大適應度','平均適應度');
string1=['最終適應度',num2str(ymax(gn))];
gtext(string1);
subplot(2,1,2);
plot(1:gn,xmax,'r-');
legend('自變量');
string2=['最終自變量',num2str(xmax(gn))];
gtext(string2);
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -