遗传算法GA的MATLAB代码

  • 格式:doc
  • 大小:28.50 KB
  • 文档页数:3

下载文档原格式

  / 7
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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;