?? my_sga_crossover.m
字號:
%交叉
% 交叉(crossover),群體中的每個個體之間都以一定的概率 pc 交叉,即兩個個體從各自字符串的某一位置
% (一般是隨機確定)開始互相交換,這類似生物進化過程中的基因分裂與重組。例如,假設2個父代個體x1,x2為:
% x1=0100110
% x2=1010001
% 從每個個體的第3位開始交叉,交又后得到2個新的子代個體y1,y2分別為:
% y1=0100001
% y2=1010110
% 這樣2個子代個體就分別具有了2個父代個體的某些特征。利用交又我們有可能由父代個體在子代組合成具有更高適合度的個體。
% 事實上交又是遺傳算法區別于其它傳統優化方法的主要特點之一。
%遺傳算法子程序
%Name: crossover.m
%交叉
function [newpop]=my_sga_crossover(popsize,chromlength,pop,pc)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% popsize=10;
% pop=[1023,980,2133,726,1946,657,1702,1224,1522,807,2025,2565,1773,2340,2354,1144,2061,240,1573,825,2025,2565,1773,2340,2354,1144,2061,240,1573,825,2025,2565,1773,2340,2354,1144,2061,240,1573,825,2025,2565,1773,2340,2354,1144,2061,240,1573,825,2025,2565,1773,2340,2354,1144,2061,240,1573,825];
% % ,2025,2565,1773,2340,2354,1144,2061,240,1573,825]
% chromlength=12;
% pc=0.96;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
pop1=pop(1,:); %將種群矩陣拆分
pop1;
pop2=pop(2,:);
pop2;
pop1=dec2bin(pop1,chromlength); %%各自轉為二進制
pop1;
pop2=dec2bin(pop2,chromlength);
pop2;
for i=1:2:popsize-1; %第1行和第2行,也就是說第1個個體和第2個個體進行交叉,依次類推
if(rand<pc)
cpoint=round(rand*chromlength);
% cpoint
if cpoint==0
cpoint=1;
end
newpop1(i,:)=[pop1(i,1:cpoint) pop1(i+1,cpoint+1:chromlength)];
newpop1(i+1,:)=[pop1(i+1,1:cpoint) pop1(i,cpoint+1:chromlength)];
else
newpop1(i,:)=pop1(i,:);
newpop1(i+1,:)=pop1(i+1,:);
end
if(rand<pc)
cpoint=round(rand*chromlength);
% cpoint
if cpoint==0
cpoint=1;
end
newpop2(i,:)=[pop2(i,1:cpoint) pop2(i+1,cpoint+1:chromlength)];
newpop2(i+1,:)=[pop2(i+1,1:cpoint) pop2(i,cpoint+1:chromlength)];
else
newpop2(i,:)=pop2(i,:);
newpop2(i+1,:)=pop2(i+1,:);
end
newpop1;
newpop2;
end
newpop1=bin2dec(newpop1);
newpop2=bin2dec(newpop2);
newpop(1,:)=newpop1';
newpop(2,:)=newpop2';
newpop;
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -