我是小鸭酱,博客地址为:http://www.cnblogs.com/xiaoyajiang
以下运用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)