Week 4.1 - Genetic Algorithm
Error is not been cleared.
Stalagmite function:
function [f] = stalagmite(input_vector)
x= input_vector(1);
y= input_vector(2);
f1 = (sin(5.1*pi*+0.5)).^6;
f2 = exp(-4*log (2)*((x-0.0667).^2/(0.64)));
f3 = (sin(5.1*pi*y + 0.5)).^6;
f4 = exp(-4*log(2)*((y-0.0667).^2/(0.64)));
f = -(f1*f2*f3*f4);
end
Program for calculating A global Maxima of a Stalagmite function using Genetic Algorithm:
clear all
close all
clc
% defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_cases = 50;
% creating a 2dimensional 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 (input_vector);
end
end
figure(1)
surfc(xx,yy,-f)
shading interp
xlabel('x-value')
ylabel('y-value')
colorbar
[inputs,fval] = ga(@stalagmite,2);
num_cases= 50;
% study1- statistical behaviour
tic
for i = 1:num_cases
[inputs,fopt(i)] = ga(@stalagmite,2);
xopt(i) = inputs(1);
yopt(i) = inputs(2);
end
study_time = toc
figure (2)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
xlabel ('x-value');
ylabel ('y-value');
plot3(xopt,yopt,-fopt,'marker','o', 'markarsize' , 5, 'markarfacecolor','r')
title ('unbounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('Iteration')
ylabel('Function minimum')
colorbar
% study 2 - statistical behaviour - with upper and lower bounds
for i = 1: num_cases
[inputs ,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
xopt(i) = inputs(1);
yopt(i) = inputs(2);
end
study_time = toc
figure (3)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o', 'markarsize' , 5, 'markarfacecolor','r')
title('Bounded inputs')
subplot(2,1,2)
shading interp
plot(-fopt)
xlabel('Iterations')
ylabel('Function maximum')
colorbar
% study 3 -Increasing GA Iterations
tic
for i = 1:num_cases
options = optimoptions('ga');
options = optimoptions (options,'PopulationsSize',250);
[inputs, fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],options);
xopt(i) = inputs(1);
yopt(i) = inputs(2);
end
study_time = toc
figure(4)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
xlabel('x-value')
ylabel('y-value')
plot3(xopt,yopt,-fopt,'marker','o', 'markarsize' , 4, 'markarfacecolor','r')
title ('Bounded inputs')
subplot(2,1,2)
shading interp
plot(-fopt)
xlabel('Iterations')
ylabel('Function maximum')
colorbar
fprintf('The Function value')
disp(-fopt(num_cases));