Week 4.1 - Genetic Algorithm
Main code
clear all
close all
clc
% Input variables
x = linspace(0, 0.6, 150);
y = linspace(0, 0.6, 150);
num_case = 250;
% creating an arraay
[xx, yy] = meshgrid(x,y);
% loop for passing 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(input_vector);
end
end
surfc(x , y , -f)
colorbar
xlabel('x values')
ylabel('y values')
zlabel('function values')
title('stalagmite function')
shading interp
[x_output , fval] = ga(@stalagmite , 2);
% case study 1
tic
for i = 1 : num_case
[inputs , f_optima(i)] = ga(@stalagmite , 2)
x_optima(i) = inputs(1);
y_optima(i) = inputs(2);
end
case1 = toc;
figure(2)
subplot(2,1,1)
surfc(x , y, -f)
shading interp
xlabel('x values')
ylabel('y values')
zlabel('function values')
hold on
plot3(x_optima, y_optima, -f_optima, 'marker', 'o', 'markersize', 5, 'markerfacecolor', 'g')
title('unbounded input')
subplot(2, 1, 2)
plot(-f_optima);
xlabel('number of iterations')
ylabel('max. value of the function')
% case study 2
tic
for i = 1 : num_case
[inputs , f_optima(i)] = ga(@stalagmite , 2, [], [], [], [], [0;0], [0.5;0.5]);
x_optima(i) = inputs(1);
y_optima(i) = inputs(2);
end
case2 = toc;
figure(3)
subplot(2,1,1)
surfc(x , y, -f)
shading interp
xlabel('x values')
ylabel('y values')
zlabel('function values')
hold on
plot3(x_optima, y_optima, -f_optima, 'marker', 'o', 'markersize', 5, 'markerfacecolor', 'g')
title('unbounded input')
subplot(2, 1, 2)
plot(-f_optima);
xlabel('number of iterations')
ylabel('max. value of the function')
% case study 3
options = optimoptions('ga');
options = optimoptions(options, 'populationsize', 250);
tic
for i = 1 : num_case
[inputs , f_optima(i)] = ga(@stalagmite , 2, [ ], [ ], [ ], [ ], [0;0], [0.5 ; 0.5], [ ], [ ],options);
x_optima(i) = inputs(1);
y_optima(i) = inputs(2);
end
case3 = toc;
figure(4)
subplot(2,1,1)
surfc(x , y, -f)
shading interp
xlabel('x values')
ylabel('y values')
zlabel('function values')
hold on
plot3(x_optima, y_optima, -f_optima, 'marker', 'o', 'markersize', 5, 'markerfacecolor', 'g')
title('unbounded input')
subplot(2, 1, 2)
plot(-f_optima);
xlabel('number of iterations')
ylabel('max. value of the function')
Function code
function [f]= stalagmite(input_vector)
x = input_vector(1);
y = input_vector(2);
f1x =sin(5.1*pi*x + 0.5)^6;
f1y =sin(5.1*pi*y + 0.5)^6;
f2x = exp(-4*log(2)*((x- 0.0667)^2)/0.64);
f2y = exp(-4*log(2)*((y - 0.0667)^2)/0.64);
f = - f1x*f1y*f2x*f2y;
end