首页 > 代码库 > 遗传算法matlab实现
遗传算法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实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。