Matlab code for simple genetic algorithm
function genealgo
syms x
n = input ('value of n:');
Q = randi([-20 20],n,n);
p = 2*n;
i=1;
while i<=p
X(i,:)= randi([0 1],n,1); % chromosome matrix
i = i+1;
end
h=1;
u=6;
while u>1
i=1;
while i<=p
E(i,1)= X(i,:)*Q*transpose(X(i,:)); % E=
Evaluated matrix
F(i,1)= exp(E(i,1)); % F = Fitness matrix
i=i+1;
end
S=0;
i=1;
while i<=p
S=S+E(i,1); % S = sum of all
evaluations
i=i+1;
end
i=1;
while i<=p
P(i,1)= E(i,1)/S ; % P = probability matrix
i=i+1;
end
i=1;
c=0;
while i<=p;
c=c+P(i,1);
C(i,1)=c; % C = Cummulative of probability
matrix
i=i+1;
end
R=rand(p,1);
i=1;
while i<= p
j=1;
while R(i,1)> C(j,1) % roulette wheel check
j=j+1;
end
X(i,1)=X(j,1); % reprodution
i=i+1;
end
N=rand(p,1);
j=1;
i=1;
while i<=n
if (N(i,1)<0.25);
A(j,1)=i;
j=j+1;
i=i+1; % chromosomes for cross
over
else
i=i+1;
end
end
i=1;
B=X(A(1,1),:);
while i< j-2
c = randi([1 n],1,1);
X(A(i,1),c:end)= X(A(i+1,1),c:end); % cross over
i=i+1;
end
c = randi([1 n],1,1);
X(A(j-2,1),c:end)= X(B(1,1),c:end);
i=1;
j=1;
while i<= p
while j<=n
c=rand(1,1);
if c < 0.05
if X(i,j)== 0;
X(i,j)=1; % mutation
else
X(i,j)=0;
end
j=j+1;
else
j=j+1;
end
end
i=i+1;
end
i=1;
while i<=p
E(i,1)= X(i,:)*Q*transpose(X(i,:)); % E= Evaluated matrix after
a generation
i=i+1;
end
disp(E)
u=std2(E);
disp(u)
disp(Q)
disp(X)
disp(h)
h=h+1;
end
%Cross over probability taken as
0.8
%Mutation probability taken as
0.05
%Q is randomly generated with it’s
all values between 20 and -20
% standard deviataion < 1 is
taken as stopping criteria
1)
Generate chromosome-chromosome number of the population, and the initialization
value of the genes chromosome-chromosome with a random value.
2) Evaluation of fitness
value of chromosomes by calculating objective function.
3) Chromosomes selection
(roulette wheel-reproduction)
4) Crossover
5) Mutation
6) New Chromosomes
(Offspring)
7) Iterate the process
till desired offspring are obtained.
8) Solution (Best
Chromosomes)