You are on page 1of 2

//

//
//
//
//

--------------------------------------------------------Title : genetic algorithm with binary representation


Author: Estefane George Macedo de Lacerda
Last Modified: 2011-03-21
---------------------------------------------------------

// objective function
function y = objFun(x)
y = x .* sin(10*%pi*x) + 1.0;
endfunction
// decode the chromossome
function x = decode(chrom)
a = -1.0;
b = 2.0;
len = length(chrom);
d = sum( chrom .* (2.0 .^ [(len-1):-1:0]) );
x = a + d*(b-a)/(2^len-1);
endfunction
// evaluate populate
function f = evaluate(P)
[row col] = size(P);
for i=1:row
x = decode(P(i,:));
f(i) = objFun(x);
end
endfunction
// ranking and roulette wheel selection
function [Par, best] = rankAndSelect(Pop,f)
nPop = size(Pop,1);
Par = zeros(nPop,size(Pop,2));
[of oi] = gsort(f);
oPop = Pop(oi,:);
best = oPop(1,:);
fit = linspace(2,0,nPop);
// ranking
cumFit = cumsum(fit)/sum(fit);
for i=1:nPop
index = find(cumFit < rand());
Par(i,:) = oPop(index($)+1,:);
end
endfunction
// 1-point crossover
function [off1, off2] = crossover(par1, par2, pCross)
if (rand() < pCross)
len = length(par1);
point = int((len-1)*rand())+1;
off1 = [par1(1:point) par2((point+1):len)];
off2 = [par2(1:point) par1((point+1):len)];
else
off1 = par1;
off2 = par2;
end
endfunction
// mutation
function off = mutate(off, pMut)
len = length(off);

r = rand(1,len);
index = find(r < pMut);
off(index) = 1-off(index); // flip
endfunction
// -------------- main
program
------------------nPop = 30;
chromSize = 22;
nGen = 25;
pCross = 0.8;
pMut = 0.05;

//
//
//
//
//

population size
chromosome size
number of generations
crossover probability
mutation probability

printf("Minimize y = x * sin(10 * pi * x) + 1.0\n");


printf("Subject to -1.0 <= x <= 2.0\n\n");
Pop = int(2*rand(nPop,chromSize)); // initial population
f = evaluate(Pop);
[parPop, best] = rankAndSelect(Pop,f);
for i=1:nGen
for k=1:2:(nPop-1)
off1 = parPop(k,:);
off2 = parPop(k+1,:);
[off1,off2] = crossover(off1,off2,pCross);
off1 = mutate(off1,pMut);
off2 = mutate(off2,pMut);
Pop(k,:) = off1;
Pop(k+1,:) = off2;
end
Pop(1,:) = best; // elitism
f = evaluate(Pop);
[parPop, ibest] = rankAndSelect(Pop,f);
printf("gen = %d, x = %f, f(x) = %f\n",i,decode(best),max(f));
end

Related Searches:
Rio De Janeiro Carnival
Flights To Rio De Janeiro
Rio De Janeiro Travel
Ponta Negra
Ponta Negra Beach
Hotels In Rio De Janeiro
Rio De Janeiro Hotels
Rio De Janeiro Travel Guide
Hotel Rio

You might also like