?? cross.m
字號:
function Ret=Cross(PCross,LenChrom,Individuals,SizePop,Opts,Pop)
% In this function,it fulfils a crossover among Chromosomes
% PCross input : probability of crossover
% LenChrom input : Length of a Chromosome
% Chrom input : set of Ret Chromosomes
% SizePop input : size of population
% Opts input : tag for choosing method of crossover
% Pop input : current serial number of generation and maximum gemeration
% Ret output : new set of Chromosome
switch Opts
case 'simple' % cross at single position
for i=1:SizePop
% select two children at random
Pick=rand(1,2);
Index=ceil(Pick.*SizePop);
while prod(Pick)==0 | Index(1)==Index(2)
Pick=rand(1,2);
Index=ceil(Pick.*SizePop);
end
% probability of crossover
Pick=rand;
if Pick>PCross
continue;
end
% random position of crossover
Pick=rand;
while Pick==0
Pick=rand;
end
Pos=ceil(Pick.*sum(LenChrom));
Tail1=bitand(Individuals.Chrom(Index(1)),2.^Pos-1);
Tail2=bitand(Individuals.Chrom(Index(2)),2.^Pos-1);
Individuals.Chrom(Index(1))=Individuals.Chrom(Index(1))-Tail1+Tail2;
Individuals.Chrom(Index(2))=Individuals.Chrom(Index(2))-Tail2+Tail1;
end
Ret=Individuals.Chrom;
case 'uniform' % uniform cross
for i=1:SizePop
% select two children at random
Pick=rand(1,2);
while prod(Pick)==0
Pick=rand(1,2);
end
Index=ceil(Pick.*SizePop);
% random position of crossover
Pick=rand;
while Pick==0
Pick=rand;
end
if Pick>PCross
continue;
end
% random position of crossover
Pick=rand;
while Pick==0
Pick=rand;
end
Mask=2^ceil(Pick*sum(LenChrom));
Chrom1=Individuals.Chrom(Index(1));
Chrom2=Individuals.Chrom(Index(2));
for j=1:sum(LenChrom)
v=bitget(Mask,j); % from lower to higher bit
if v==1
Chrom1=bitset(Chrom1,...
j,bitget(Individuals.Chrom(Index(2)),j));
Chrom2=bitset(Chrom2,...
j,bitget(Individuals.Chrom(Index(1)),j));
end
end
Individuals.Chrom(Index(1))=Chrom1;
Individuals.Chrom(Index(2))=Chrom2;
end
Ret=Individuals.Chrom;
case 'float'
for i=1:SizePop
% select two children at random
Pick=rand(1,2);
while prod(Pick)==0
Pick=rand(1,2);
end
Index=ceil(Pick.*SizePop);
% random position of crossover
Pick=rand;
while Pick==0
Pick=rand;
end
if Pick>PCross
continue;
end
% random position of crossover
Pick=rand;
while Pick==0
Pick=rand;
end
Pos=ceil(Pick.*sum(LenChrom));
Pick=rand;
V1=Individuals.Chrom(Index(1),Pos);
V2=Individuals.Chrom(Index(2),Pos);
Individuals.Chrom(Index(1),Pos)=Pick*V2+(1-Pick)*V1;
Individuals.Chrom(Index(2),Pos)=Pick*V1+(1-Pick)*V2;
end
Ret=Individuals.Chrom;
end
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -