Genetic Algorithm in Matlab

5 views (last 30 days)
Devraj Mandal
Devraj Mandal on 17 Jul 2013
Genetic Algorithm in Matlab : Basic Implementation .
%%steps
%1.Initialize the populations
tic
clc; clear all; close all;
par_size=6;
%Encode
for i=1:par_size
par(i,:)=dec2bin(round(1+1023*rand),10);
a(i) = bin2dec(par(i,:));
end
for iter = 1:100
%2.Evaluate fitness
fitness = zeros(1,par_size);
%The fitness function
%count the no of one's in the string
fitness = [sum(par=='1',2)].';
sum_fitness = sum(fitness)
prob_fitness = fitness./sum_fitness;
[~,I]=sort(prob_fitness);
%I is the order of the fitness value
prob_fitness_sort = prob_fitness(I);
%sorting
par = par(I,:);
%3.Select Parents
%Roulette wheel selection
%generate cumulative probability
cum_prob = zeros(size(prob_fitness));
A = zeros(size(prob_fitness));
for i=1:par_size
A(i) = prob_fitness_sort(i);
cum_prob(i) = sum(A);
end
new_pop = par;
%Selection being done
r1 = zeros(1,par_size);
for i=1:par_size
r1(i) = rand;
if r1(i)<=cum_prob(1)
new_pop(i,:) = par(1,:);
elseif r1(i)>cum_prob(1) && r1(i)<=cum_prob(2)
new_pop(i,:) = par(2,:);
elseif r1(i)>cum_prob(2) && r1(i)<=cum_prob(3)
new_pop(i,:) = par(3,:);
elseif r1(i)>cum_prob(3) && r1(i)<=cum_prob(4)
new_pop(i,:) = par(4,:);
elseif r1(i)>cum_prob(4) && r1(i)<=cum_prob(5)
new_pop(i,:) = par(5,:);
elseif r1(i)>cum_prob(5) && r1(i)<=cum_prob(6)
new_pop(i,:) = par(6,:);
end
end
%new_pop is the new particle sample
%4.Crossover and Mutate
%crossover
pc = 0.6; %pc is the crossover probability
for i=1:2:par_size %selecting adjacent couples
r2 = rand;
if r2<=pc
l = size(new_pop, 2);
%choose the parents
%here adjacent parents are taken
breeders(1,:)=new_pop(i,:);
breeders(2,:)=new_pop(i+1,:);
%choose a crossover point
cp = randperm(l, 1);
[i,cp];
%do crossover
b1 = [breeders(1, 1:cp), breeders(2, cp+1:end)];
b2 = [breeders(2, 1:cp), breeders(1, cp+1:end)];
new_pop(i,:) = b1;
new_pop(i+1,:) = b2;
end
end
%mutation
%pm be mutation probability
pm = 0.1;
for i=1:par_size
r2 = rand;
if r2<=pm %mutation probability is 0.1
%Do mutation
%select random position
r3 = 1+round((10-1)*rand);
[i,r3];
new_pop(i,r3)=num2str(abs(str2num(new_pop(i,r3))-1));
end
end
par = new_pop;
end
Is it correct ? Can it be improved ??

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!