⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 crossover.m

📁 基本的遗传算法实现
💻 M
字号:
%交叉操作
function [NewPop]=CrossOver(OldPop,pcross)%OldPop为父代种群,pcross为交叉概率
[m,n]=size(OldPop);
r=rand(1,m);
y1=find(r<pcross);
y2=find(r>=pcross);
len=length(y1);
if len>2&mod(len,2)==1%如果用来进行交叉的染色体的条数为奇数,将其调整为偶数
y2(length(y2)+1)=y1(len);
y1(len)=[];
end
if length(y1)>=2
for i=0:2:length(y1)-2
[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=EqualCrossOver(OldPop(y1(i+1),:),OldPop(y1(i+2),:));
end 
end
NewPop(y2,:)=OldPop(y2,:);

function [children1,children2]=EqualCrossOver(parent1,parent2)
%采用均匀交叉 例:
%父1:0 1 1 1 0 0 1 1 0 1 0
%父2:1 0 1 0 1 1 0 0 1 0 1
%掩码:0 1 1 0 0 0 1 1 0 1 0
%交叉后新个体:
%子1:1 1 1 0 1 1 1 1 1 1 1 
%子2:0 0 1 1 0 0 0 0 0 0 0
L=length(parent1);
hidecode=round(rand(1,L));%随机生成掩码,如hidecode=[0 1 1 0 0 0 1 1 0 1 0];
children1=zeros(1,L);
children2=zeros(1,L);
children1(find(hidecode==1))=parent1(find(hidecode==1));%掩码为1,父1为子1提供基因
children1(find(hidecode==0))=parent2(find(hidecode==0));%掩码为0,父2为子1提供基因
children2(find(hidecode==1))=parent2(find(hidecode==1));%掩码为1,父2为子2提供基因
children2(find(hidecode==0))=parent1(find(hidecode==0));%掩码为0,父1为子2提供基因

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -