Week 5 - Genetic Algorithm
stalagmite function:
function [f] = stalagmite(input_vector)
x = input_vector(1);
y = input_vector(2);
fx1 = (sin((5.1*pi*x)+0.5)).^6;
fy1 = (sin((5.1*pi*y)+0.5)).^6;
fx2 = exp(-4*log(2)*(((x-0.067).^2)/0.64));
fy2 = exp(-4*log(2)*(((y-0.067).^2)/0.64));
f = -(fx1.*fy1.*fx2.*fy2);
end
clear
close
clc
%defining the input space
x = linspace(0,0.5,150);
y = linspace(0,0.5,150);
%no of iterations is set to 50
num_case = 50;
[xx,yy] = meshgrid(x,y);
%assigning the values to inputs
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
%ploting
figure(1)
surfc(xx,yy,-f)
%using shading interp to remove the mesh
shading interp
%using hold on to present all the peaks in one plot
hold on
%difining x,y axis and title
xlabel('x value')
ylabel('y value')
zlabel('population density')
title('stalagmite')
%case 1: unbounded
% using tic and tok to calculate the time taken
tic
for z = 1:num_case
[inputs, fopt(z)] = ga(@stalagmite,2);
xopt(z) = inputs(1);
yopt(z) = inputs(2);
end
study2_time = toc
figure(2)
subplot(2,1,1)
hold on
surfc(x,y,f)
shading interp
plot3(xopt,yopt,fopt,'Marker','o','markersize',5,'markerfacecolor','r')
title('unbounded inputs')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('function minimum')
%case 2:bounded case with lower and upper limits
tic
for z = 1:num_case
[inputs, fopt(z)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.5;0.5]);
xopt(z) = inputs(1);
yopt(z) = inputs(2);
end
study3_time = toc
figure(3)
subplot(2,1,1)
hold on
surfc(x,y,f)
shading interp
plot3(xopt,yopt,fopt,'Marker','o','markersize',5,'markerfacecolor','g')
title('bounded inputs')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('function minimum')
%case 3: bounded and population 200
options = optimoptions('ga');
options = optimoptions(options,'PopulationSize', 200);
tic
for z = 1:num_case
[inputs, fopt(z)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.5;0.5],[],[],options);
xopt(z) = inputs(1);
yopt(z) = inputs(2);
end
study4_time = toc
figure(4)
subplot(2,1,1)
hold on
surfc(x,y,f)
shading interp
plot3(xopt,yopt,fopt,'Marker','o','markersize',5,'markerfacecolor','y')
title('bounded inputs')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('function minimum')
command window:
study2_time =
3.0724
study3_time =
4.5862
study4_time =
14.3310
trail 2:
study2_time =
3.5504
study3_time =
6.7584
study4_time =
26.4160
ga syntax: ga(function,no.of variables,[constrants],[c],[c],[c],[lower boundry],[upper boundry],[non-linear constrants],[nlc],options)