遗传算法matlab实现
Posted 小鸭酱的书签
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了遗传算法matlab实现相关的知识,希望对你有一定的参考价值。
clc
clear
%参数
a = 0 ;
b = 4 ;
eps = 0.01 ;
lenchrom = ceil(log2((b - a)/eps + 1)) ;
sizepop = 50 ;
maxgen = 500 ;
pcross = 0.9 ;
pm = 0.05 ;
fitness = ones(1,sizepop) ;
chrom = zeros(sizepop,lenchrom) ;
nx = zeros(sizepop,lenchrom) ;
%初始化
%随机产生一个种群
for i = 1 : sizepop
for j = 1 : lenchrom
chrom(i,j) = round(rand) ;
end
x = a + (b - a) * (dot( 2 .^ ((lenchrom - 1) : -1 : 0 ) , chrom(i,:)) ) / ( 2 ^ lenchrom - 1) ;
fitness(i) = fun(x);
end
[bestfitness , bestindex] = max(fitness);
bestchrom = chrom(bestindex,:) ;
for i = 1 : maxgen
%select
sumfitness = sum(fitness) ;
fit = fitness ./ sumfitness ;
tfit = zeros(sizepop) ;
tfit(1) = fit(1) ;
for j = 2 : sizepop
tfit(j) = tfit(j - 1) + fit(j) ;
end
for k = 1 : sizepop
pick = rand ;
if pick < fit(1)
father = 1 ;
else
for l = 1 : (sizepop - 1 )
if pick > tfit(l) && pick < tfit(l + 1)
father = l + 1 ;
end
end
end
mother = ceil(rand * sizepop) ;
%cross
pick = rand ;
if pcross > pick
poscross = randperm(lenchrom,1) ;
nx(k,1:poscross) = chrom(father,1:poscross) ;
nx(k,(poscross + 1):lenchrom) = chrom(mother,(poscross + 1):lenchrom) ;
else
nx(k,:) = chrom(father,:) ;
end
%mutation
index = randperm(sizepop,1) ;
pick = rand ;
if pick < pm
posm = randperm(lenchrom,1) ;
chrom(index,posm) = ~chrom(index,posm) ;
end
end
chrom = nx ;
for j = 1 : sizepop
x = a + (b - a) * (dot( 2 .^ ((lenchrom - 1) : -1 : 0 ) , chrom(j,:)) ) / ( 2 ^ lenchrom - 1) ;
fitness(j) = fun(x) ;
end
[newbestfitness , newbestindex] = max(fitness) ;
if newbestfitness > bestfitness
bestfitness = newbestfitness ;
bestindex = newbestindex ;
bestchorm = chrom(bestindex,:) ;
end
end
bestx = a + (b - a) * (dot( 2 .^ ((lenchrom - 1) : -1 : 0 ) , bestchrom) ) / ( 2 ^ lenchrom - 1)
bestf = bestx * sin(bestx)
以上是关于遗传算法matlab实现的主要内容,如果未能解决你的问题,请参考以下文章