Week 4.1 - Genetic Algorithm
% the stalagmite function and its working is explained in the doc file report attached.
function solution = stalagmite(inputs)
x = inputs(1);
y = inputs(2);
fxone = (sin(((5.1*pi).*x)+0.5)).^6;
fxtwo = exp((((x-0.0667).^2).*(-4*log(2)))./0.64);
fyone = (sin(((5.1*pi).*y)+0.5)).^6;
fytwo = exp((((y-0.0667).^2).*(-4*log(2)))./0.64);
solution = -((fxone)*(fxtwo)*(fyone)*(fytwo)); % we use a negative sign to attain a maximum value
end
%% the explanation for all the cases has been explained in the report, this includes all the figures or the outputs for the respective cases.
clear all
close all
clc
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
number_of_cases= 50; % number of times the stalagmite function is run
[xx,yy] = meshgrid(x,y);
for i = 1: length(xx)
for j= 1: length(yy)
input(1) = xx(i,j);
input(2) = yy(i,j);
f(i,j) = stalagmite(input);
end
end
% Case 1: Unbounded
% fopt is the optimum value the function predicts
for i = 1:number_of_cases
[inputs, fopt(i)]= ga(@stalagmite, 2) %here 2 is the number of variable for the ga syntax and we are calling the stalagmite function in this syntax
%now we store the x and y inputs
xopt(i)= inputs(1);
yopt(i)= inputs(2);
end
figure(1)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt, yopt, -fopt, 'marker', 'o','markersize',5,'markerfacecolor','r')
title('unbounded inpupts')
%in the second plot we directly plot the optimum value the function produce
subplot(2,1,2)
plot(-fopt)
xlabel('number of iterations')
ylabel('function maximum')
% Upper and lower bounds
for i = 1:number_of_cases
[inputs, fopt(i)]= ga(@stalagmite, 2, [],[],[],[],[0;0],[1:1]);
xopt(i)= inputs(1);
yopt(i)= inputs(2);
end
figure (2)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
plot3(xopt, yopt, -fopt,'marker', 'o','markersize',5,'markerfacecolor','r')
title(' Case 2: bounded inpupts')
%in the second plot we directly plot the optimum value the function produce
subplot(2,1,2)
plot(-fopt)
xlabel('number of iterations')
ylabel('function maximum')
%case 3: when size of the population is increased:
% ga syntax is explained in the wod doc. attached
options = optimoptions('ga');
options = optimoptions(options, 'PopulationSize', 170);
for i = 1:number_of_cases
[inputs, fopt(i)]= ga(@stalagmite, 2, [],[],[],[],[0;0],[1:1],[],[], options);
xopt(i)= inputs(1);
yopt(i)= inputs(2);
end
figure (3)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
plot3(xopt, yopt, -fopt,'marker', 'o','markersize',5,'markerfacecolor','r')
title(' Case 3: increasing the population size to find gloabl maxima')
%in the second plot we directly plot the optimum value the function produce
subplot(2,1,2)
plot(-fopt)
xlabel('number of iterations')
ylabel('function maximum')