加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

matlab实现算法代码:GA(遗传算法)——整数编码

(2008-06-10 11:26:19)
标签:

it

分类: matlab交流专区

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;

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有