f ( x ) = 11 s i n ( 6 x ) + 7 c o s ( 5 x ) , x ∈ [ − π , π ] f(x) = 11sin(6x)+7cos(5x), x\in[-\pi,\pi] f(x)=11sin(6x)+7cos(5x),x∈[−π,π]
clc,clear,close all
lb = -1;
ub = 2;
f = @(x) 11 * sin(6*x) + 7 * cos(5*x);
popsize = 20;
chromlength = 16;
pc = 0.7;
pm = 0.02;
generation = 20;
pop = initpop(popsize,chromlength);
fplot(f,[lb,ub])
hold on
BestIndividual = zeros(generation,1);
BestFitness = zeros(generation,1);
for i = 1:generation
[~,phenotype] = gene2pheno(pop,f,lb,ub,chromlength);
fitvalue = fitness(phenotype,popsize);
pop = select(pop,fitvalue);
pop = crossover(pop,pc);
pop = mutate(pop,pm);
[BestIndividual(i),BestFitness(i)] = FindBest(pop,f,lb,ub,chromlength);
disp(['第',num2str(i),'代'])
disp(['最大值点:',num2str(BestIndividual(i))])
disp(['最大值:',num2str(BestFitness(i))])
plot(BestIndividual(i),BestFitness(i),'r*')
end
f2 = @(x) -f(x) ;
[x,fval] = ga(f2,1,[],[],[],[],lb,ub) %matlab自带遗传算法工具箱
plot(x,-fval,'gd')
function pop = initpop(popsize, chromlength)
pop = round(rand(popsize,chromlength));
end
function pop2 = decodebinary(pop)
py = size(pop,2);
pop1 = pop*2.^(0:(py-1))';
pop2 = sum(pop1,2);
end
function pop2 = decodechrom(pop,spoint,genelength)
pop1 = pop(:,spoint:spoint + genelength - 1);
pop2 = decodebinary(pop1);
end
function [genetype,phenotype] = gene2pheno(pop,f,lb,ub,chromlength)
temp1 = decodechrom(pop,1,chromlength);
genetype = lb + (ub-lb)/(2^chromlength-1) *temp1;
phenotype = f(genetype);
end
function fitvalue = fitness(phenotype)
Cmin = 0;
fitvalue = phenotype + Cmin;
fitvalue(fitvalue < 0) = 0;
end
function newpop = select(pop,fitvalue)
fitvalue = cumsum(fitvalue/sum(fitvalue));
px = size(pop,1);
newpop = pop;
SelectRate = sort(rand(px,1));
FitIdx = 1;
NewIdx = 1;
while NewIdx <= px
if SelectRate(NewIdx) < fitvalue(FitIdx)
newpop(NewIdx,:) = pop(FitIdx,:);
NewIdx = NewIdx + 1;
else
FitIdx = FitIdx + 1;
end
end
end
function newpop = crossover(pop,pc)
[px,py] = size(pop);
newpop = pop;
for i = 1:2:px-1
if rand < pc
cpoint = ceil(rand * py);
newpop(i,cpoint+1:end) = pop(i+1,cpoint+1:end);
newpop(i+1,cpoint+1:end) = pop(1,cpoint+1:end);
end
end
end
function newpop = mutate(pop,pm)
[px,py] = size(pop);
newpop = pop;
for i = 1:px
if(rand < pm)
mpoint = ceil(rand * py);
newpop(i,mpoint) = ~pop(i,mpoint);
end
end
end
function [BestIndividual,BestFitness] = FindBest(pop,f,lb,ub,chromlength)
[genetype,phenotype] = gene2pheno(pop,f,lb,ub,chromlength);
[BestFitness, BestIdx] = max(phenotype);
BestIndividual = genetype(BestIdx);
end