Week 4.1 - Genetic Algorithm
AIM: To write a code in matlab to optimize the stalagmite function and find the global maxima of the function.
PRE-REQUISITE KNOWLEDGE: The genetic algorithm is an algorithm used for solving both constrained and unconstrained optimization problems. It selects random inputs called as population, check their fitness for selection and pairing purposes to generate new data. This next generation data is mutated from data acquired from parent which is essential for computing optimized output.
The genetic algorithm uses 3 main types of rules at each step to create the next generation from the current population:
- Selection rules select the individuals called parents that contribute to the population at the next generation.
- Crossover rules combine two parents to form children for the next generation.
- Mutation rules apply random changes to individual parents to form children.
clear all
close all
clc
x = linspace(0, 0.6, 150);
y = linspace(0, 0.6, 150);
[xx, yy] = meshgrid(x, y);
num_cases = 50;
for i = 1:length(xx)
for j = 1:length(yy)
input_vector(1) = xx(i, j);
input_vector(2) = yy(i, j);
f(i, j) = stalagmite(input_vector);
end
end
tic
for i = 1:num_cases
[inputs, fopt(i)] = ga(@stalagmite,2);
xopt(i) = inputs(1);
yopt(i)=inputs(2);
end
study_time1 = toc
figure(1)
subplot(2,1,1)
hold on
surf(xx,yy,-f)
shading interp
plot3(xopt, yopt, -fopt,'marker','o','markersize',5)
xlabel('x value')
ylabel('y value')
title('Genetic Algorithm Unbound Inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Max. Value of Funtion')
title('Max. Value of Funtion vs Iterations')
%Bound Inputs
options = optimoptions('ga');
options = optimoptions(options, 'PopulationSize',50);
%iterations of genetic algorithm bound inputs
tic
for i=1:num_cases
[inputs, fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[1,1]);
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
study_time2=toc;
figure(2)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5)
xlabel('x value')
ylabel('y value')
title('Genetic Algorithm Bound Inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Max. Value of Funtion')
title('Max. Value of Funtion vs Iterations')
%Bound Inputs
options = optimoptions('ga');
options = optimoptions(options, 'PopulationSize',250);
%iterations of genetic algorithm bound inputs
tic
for i=1:num_cases
[inputs, fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[1,1],[],[],options);
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
study_time3=toc;
figure(3)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5)
xlabel('x value')
ylabel('y value')
title('Genetic Algorithm Bound Inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Max. Value of Funtion')
title('Max. Value of Funtion vs Iterations')
CONCLUSION: The code was written and executed.



