matlab for genetic algorithm

function [BestX,BestF]=agopt(N,Maxit)
% call:
%  rosen to defini objective function
% aritps: crossover operator
% lotere: select parents
%Input:
% N ; % number of kromosom in population
% Maxit ; % number of max iteration
rb = [-3 -3]; % lower bound
ra = [3 3]; % upper bound
Psilang = 0.8; % crossover rate
st=cputime;

% Inisialisasi populasi
for i=1:N
Populasi(i,:)= rb+(ra-rb).*rand(1,2);%Inisialisasi Populasi(N,2)
end
for generasi=1:Maxit,
for i=1:N
nilai(i) = rosen(Populasi(i,:));%kromosom
Fitness(i)= 1/(nilai(i)+1);
[MaxF,idk]=max(Fitness);%
MinF=min(Fitness);
BestX = Populasi(idk,:);
end

if MaxF >=100,%if fitness maximum > 100,
%stop
break;
end
Populasi_s = Populasi;
% Elitisme
% best kromosom copied 4x if population even
% 3x if odd
if mod(N,2)==0, % even size
IterasiMulai = 5;% best Individual copied 4 x
Populasi_s(1,:) = Populasi(idk,:);
Populasi_s(2,:) = Populasi(idk,:);
Populasi_s(3,:) = Populasi(idk,:);
Populasi_s(4,:) = Populasi(idk,:);

else % odd size
IterasiMulai = 4; % best individual copied 3 x
Populasi_s(1,:) = Populasi(idk,:);
Populasi_s(2,:) = Populasi(idk,:);
Populasi_s(3,:) = Populasi(idk,:);
end
nFitness=Fitness-MinF;
% Roulette-wheel selection dan pindah silang
for j=IterasiMulai:2:N,
Bapak = lotere(N,nFitness);
Ibu = lotere(N,nFitness);
if (rand < Psilang),
Anak = aritps(Populasi(Bapak,:),Populasi(Ibu,:));
Populasi_s(j,:) = Anak(1,:);
Populasi_s(j+1,:) = Anak(2,:);
else % jika tidak terjadi kawin silang
% kromosom baru berasal dari Bapak dan Ibu tanpa
% kawin silang
Populasi_s(j,:) = Populasi(Bapak,:);
Populasi_s(j+1,:) = Populasi(Ibu,:);
end
end
% Mutasi dilakukan pada sejumlah kromosom
% (50% dari populasi) secara random
for i=1:(0.5*N)
kk=4+ceil(rand*N);
Populasi_s(kk,:) = rand(1,2).*(ra-rb)+rb;
end

% mengganti sejumlah kromosom dengan kromosom baru
% hasil elitisme,kawin silang dan mutasi
Populasi = Populasi_s;

end
BestF=rosen(BestX);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
totaltime=cputime-st

function indek=lotere(N,nFitness);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
JumFitness = sum(nFitness);
KumFitness = 0;
r = rand;
i = 1;
while i <= N,
KumFitness = KumFitness + nFitness(i);
if (KumFitness/JumFitness) > r,
indek = i;
break;
end
i = i + 1;
end

function Anak = aritps(Bapak,Ibu);
%aritmatik crossoverOptimasi dan Data mi…
r=rand;
Anak(1,:) = r*Bapak + (1-r)*Ibu;
Anak(2,:) = r*Ibu +(1-r)* Bapak;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s