遗传算法GA的MATLAB代码
- 格式:doc
- 大小:28.50 KB
- 文档页数:3
MATLAB实现算法代码:GA(遗传算法)——整数编码
function [BestGene,aa] = GA(MaxGeneration,GeneSize,GeneNum,pcross,pmute,minGene,maxGene)
Parent = Init(GeneSize,GeneNum,minGene,maxGene);
[BestGene,Parent] = KeepBest(Parent);
aa = [];
for i = 1:MaxGeneration
[i 1/value(BestGene)]
Child = chose(Parent);
Child = cross(Child,pcross);
Child = mute(Child,pmute,maxGene);
[BestGene,Parent] = KeepBest(Child);
aa = [aa;value(BestGene)];
end
function GeneInit = Init(GeneSize,GeneNum,minGene,maxGene)
GeneInit = [];
for i = 1:GeneSize
x = []; x = ceil(rand(1,GeneNum).*(maxGene-minGene)) + minGene;
GeneInit = [GeneInit;x];
end
GeneInit = [GeneInit;x];
function Child = chose(Parent)
GeneSize = size(Parent,1);
for i = 1:GeneSize
x = Parent(i,:);
val(i) = value(x);
end
ValSum = sum(val);
val = val / ValSum;
for i = 2:GeneSize
val(i) = val(i) + val(i-1);
end
for i = 1:GeneSize
randval = rand;
if randval <= val(1)
Child(i,:) = Parent(1,:);
end
for j = 2:GeneSize
if randval > val(j-1) && randval <= val(j)
Child(i,:) = Parent(j,:);
break;
end
end
end
Child(end,:) = Parent(end,:);
function Child = cross(Parent,pcross)
[GeneSize,GeneNum] = size(Parent);
GeneSize = GeneSize - 1;
Child = Parent;
for i = 1:GeneSize/2
if rand < pcross
flag = 0;
while( flag==0 )
randval1 = floor((GeneNum-1)*rand) + 1;
randval2 = floor((GeneNum-1)*rand) + 1;
if randval1 ~= randval2
flag = 1;
end
end
temp = Child(2*i-1,randval1:randval2);
Child(2*i-1,randval1:randval2) = Child(2*i,randval1:randval2);
Child(2*i,randval1:randval2) = temp;
end
end
function Child = mute(Parent,pmute,maxGene)
[GeneSize,GeneNum] = size(Parent);
GeneSize = GeneSize - 1;
Child = Parent;
for i = 1:GeneSize
if rand < pmute
randval = ceil((GeneNum-1)*rand) + 1;
Child(i,randval) = maxGene(randval) - Child(i,randval) + 1;
end
end
function [BestGene,Parent] = KeepBest(Child)
[GeneSize,GeneNum] = size(Child);
for i = 1:GeneSize
x = Child(i,:);
val(i) = value(x);
end
BigVal = val(1);
flag = 1;
for i = 2:GeneSize
if BigVal < val(i)
BigVal = val(i);
flag = i;
end
end
BestGene = Child(flag,:); Parent = Child;
Parent(1,:) = BestGene; Parent(end,:) = BestGene;