Week 4.1 - Genetic Algorithm
clear all
close all
clc
% Assiging values for x and y
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
[xx yy] = meshgrid(x,y);
% Number of iterations
iterations = 50;
% Surface plot
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
% first iteration
tic
for i = 1:iterations
[inputs, f_opt(i)] = ga(@stalagmite,2);
x_opt(i) = inputs(1);
y_opt(i) = inputs(2);
end
first_iteration_time = toc
% plot
figure (1)
subplot(2,1,1)
hold on
surfc(xx,yy,f)
% Applying shading to the plot instead of default grid lines
shading interp
plot3(x_opt,y_opt,f_opt,'marker','o','markersize',4,'markerfacecolor','r')
title('unbounded inputs');
subplot(2,1,2)
plot(f_opt)
xlabel('iterations')
ylabel('function maxima')
% second iteration
tic
for i = 1:iterations
[inputs, f_opt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
x_opt(i) = inputs(1);
y_opt(i) = inputs(2);
end
second_iteration_time = toc
% plot
figure (2)
subplot(2,1,1)
hold on
surfc(xx,yy,f)
% Applying shading to the plot instead of default grid lines
shading interp
plot3(x_opt,y_opt,f_opt,'marker','o','markersize',4,'markerfacecolor','r')
title('bounded inputs');
subplot(2,1,2)
plot(f_opt)
xlabel('iterations')
ylabel('function maxima')
% Third iteration for population size
options = optimoptions('ga');
options = optimoptions(options,'populationsize',200) % Increasing the size of the population
tic
for i = 1:iterations
[inputs, f_opt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],options);
x_opt(i) = inputs(1);
y_opt(i) = inputs(2);
end
third_iteration_time = toc
% plot
figure (3)
subplot(2,1,1)
hold on
surfc(xx,yy,f)
% Applying shading to the plot instead of default grid lines
shading interp
plot3(x_opt,y_opt,f_opt,'marker','o','markersize',4,'markerfacecolor','r')
title('bounded inputs with different population size');
subplot(2,1,2)
plot(f_opt)
xlabel('iterations')
ylabel('function maxima')
Stalagmite function
function [F] = stalagmite(input_vector)
x = input_vector(1);
y = input_vector(2);
f1_x = (sin(5.1*pi*x+0.5)).^6;
f1_y = (sin(5.1*pi*y+0.5)).^6;
f2_x = exp((-4*log(2)*(x-0.667).^2)/(0.64));
f2_y = exp((-4*log(2)*(y-0.0667).^2)/(0.64));
F = -(f1_x*f2_x*f1_y*f2_y);
end


