📄 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 + -