Week 4.1 - Genetic Algorithm
% program to optimise the stalagmite function and find the global maxima of the function
close all
clear all
clc
% defining our search space
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
% creating 2D mesh
[xx, yy]=meshgrid(x,y);
% no. of times ga run
n=50;
% evaluating the stalagmate function
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
figure(1)
hold on
surfc (xx,yy,-f)
xlabel('x axis')
ylabel ('y axis')
title('stalagmite function')
shading interp
%study 1 - Unbounded Condition
tic
for i=1:n
[inputs,fopt(i)]=ga(@stalagmite,2);
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
Study_time_1 = toc
figure(2)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
ylabel('y axis');
xlabel('x axix');
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('unbounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations');
ylabel('Function maximum');
%study 2- with upper and lower bounds
tic
for i=1:n
[inputs,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6]);
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
Study_time_2 = toc
figure(3)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
xlabel('x axis');
ylabel('y axis');
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('unbounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations');
ylabel('Function maximum');
%study 3 - Increasing GA Iterations
options=optimoptions('ga')
options=optimoptions(options,'PopulationSize',500);
tic
for i=1:n
[inputs,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
study3_time=toc
figure(4)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
xlabel('x axis')
ylabel('y axis')
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('Bounded Inputs with Modified Population Size')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations');
ylabel('Function maximum');