v2=chrom(index(2),pos);
chrom(index(1),pos)=pick*v2+(1-pick)*v1;
chrom(index(2),pos)=pick*v1+(1-pick)*v2; %交叉结束
flag1=test(lenchrom,bound,chrom(index(1),:)); %检验染色体1的可行性 flag2=test(lenchrom,bound,chrom(index(2),:)); %检验染色体2的可行性 if flag1*flag2==0 flag=0; else flag=1;
end %如果两个染色体不是都可行,则重新交叉 end end
ret=chrom;
Code
function ret=Code(lenchrom,bound)
%本函数将变量编码成染色体,用于随机初始化一个种群 % lenchrom input : 染色体长度
% bound input : 变量的取值范围 % ret output: 染色体的编码值
flag=0;
while flag==0
pick=rand(1,lenchrom);
ret=bound(:,1)'+(bound(:,2)-bound(:,1))'.*pick; %线性插值
flag=test(lenchrom,bound,ret); %检验染色体的可行性 end
Select2
function ret=Select(individuals,fitness,sizepop)
% 本函数对每一代种群中的染色体进行选择,以进行后面的交叉和变异 % individuals input : 种群信息 % fitness input : 适应度
% sizepop input : 种群规模
% opts input : 选择方法的选择 % ret output : 经过选择后的种群
fitness= 1./(fitness);
sumfitness=sum(fitness); sumf=fitness./sumfitness; index=[];
for i=1:sizepop %转sizepop次轮盘 pick=rand;
while pick==0 pick=rand; end
for j=1:sizepop pick=pick-sumf(j); if pick<0
index=[index j];
break; %寻找落入的区间,此次转轮盘选中了染色体i,注意:在转sizepop次轮盘的过程中,有可能会重复选择某些染色体 end end end
individuals=individuals(index,:); fitness=fitness(index); ret=individuals;
test
function flag=test(lenchrom,bound,code) % lenchrom input : 染色体长度
% bound input : 变量的取值范围 % code output: 染色体的编码值
flag=1;
[n,m]=size(code);
fori=1:n
if code(i)