fplot('x+10*sin(5*x)+7*cos(4*x)',[0 9])
function result=reproduce(population)
% Returns next generation of a population
fitted_pop=distribution(population);
for i=1:(size(population,1)/2)
x=select(fitted_pop);
y=select(fitted_pop);
[x,y]=crossover(x,y);
result(2*i-1,:)=x;
result(2*i,:)=y;
end
function_result=select(popWithDistrib)
% Select some genotypes from the population,
% and possibly mutates them.
selector=rand;
total_prob=0;
% Default to last in case of rounding error
genotype=popWithDistrib(end,2:end);
for i=1:size(popWithDistrib,1)
total_prob=total_prob+popWithDistrib(i,1);
if total_prob > selector
genotype=popWithDistrib(i,2:end);
break;
end
end
result=mutate(genotype);
function [x,y]=crossover(x,y)
% Possibly takes some information from one genotype and
% swaps it with information from another genotype
if rand < 0.6
gene_length=size(x,2);
% site is between 2 and gene_length
site=ceil(rand * (gene_length-1))+1;
tmp=x(site:gene_length);
x(site:gene_length)=y(site:gene_length);
y(site:gene_length)=tmp;
end
function result=fitness(population);
% Returns the fitness for each row in a population
result=sum(population, 2);
function result=distribution(population)
% Takes the population data and returns the population
% data with each genotype paired with its fraction of
% the total fitness of the population
genotypes=noduplicates(population);
total fitness=sum(fitness(genotypes));
result=[(fitness(genotypes)/total fitness), genotypes];
function result=mutate(genotype)
% Possibly mutates a genotype
result=abs(genotype - rand(size(genotype,1),
size(genotype,2))<0.03));
function [sol, val]=gaDemo1Eval(sol,options)
x=sol(1);
val=x+10*sin(5*x)+7*cos(4*x);
function [pop]=initializega(populationSize, variableBounds,evalFN, evalOps,options)
initPop=initializega(10,[0 9],'ga');
hold on
plot (initPop(:,1),initPop(:,2),'g+')
function [x,endPop,bPop,traceInfo]=ga(bounds,evalFN,evalOps,startPop,opts,termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)
[x endPop]=ga([0 9],’ga’,[],initPop,[1e-6 11],’maxGenTerm’,1,... ’normGeomSelect’,[0.08],[’arithXover’],[2 0],’nonUnifMutation’,[2 1 3]);