Week 4.1 - Genetic Algorithm
%defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_cases = 50;
%creating 2d mesh
[xx, yy] = meshgrid(x,y);
%evaluating the stalagmite 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_func(input_vector);
end
end
figure(1)
surf(xx,yy,f)
shading interp
[x,fval] = ga(@stalagmite_func,2);
xlabel('x values');
ylabel('y values');
title('stalagmit function')
tic
for i = 1:num_cases
[inputs,fopt(i)] = ga(@stalagmite_func,2);
xopt(i) = inputs(1);
yopt(i) = inputs(2);
end
study1_time = toc
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('unbounded input')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('function maximum')
tic
%study 2- statistical behavior - with upper and lower bond
for i = 1: num_cases;
[input,fopt(i)] = ga(@stalagmite_func,2,[],[],[],[],[0,0],[1,1]);
xopt(i) = input(1);
yopt(i) = input(2);
end
study2_time = toc
figure(3)
subplot(2,1,1)
hold on
surf(xx,yy,f)
shading interp
plot3(xopt,yopt,fopt,'Marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('bounded input')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('function maxima')
tic
%case3 increased interations using bonded values using ga
option = optimoptions('ga')
option = optimoptions(option,'PopulationSize',170)
tic
for i = 170
[input,fopt(i)] = ga(@stalagmite_func,2,[],[],[],[],[0;0],[1;1],[],[],option)
xopt(i) = input(1)
yopt(i) = input(2)
end
study3_time = toc
figure(4)
subplot(2,1,1)
hold on
surfc(xx,yy,f)
shading interp
plot3(xopt,yopt,fopt,'Marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('increased ga iterations')
subplot(2,1,2)
plot(fopt)
xlabel ('iteration')
ylabel('function maxima')
FUNCTION
function [f] = stalagmite_func(input_vector)
x = input_vector(1);
y = input_vector(2);
f1 = (sin(5.1*pi*x + 0.5))^6;
f2 = (sin(5.1*pi*y + 0.5))^6;
f3 = exp((-4*log(2)*((x-0.0667)^2)/0.64));
f4 = exp((-4*log(2)*((y-0.0667)^2)/0.64));
f = (-f1*f2*f3*f4);
end