Week 4.1 - Genetic Algorithm
GENECTIC ALGORITHM CODE
clear all
close all
clc
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
[xx,yy] = meshgrid(x,y);
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
num_cases = 50;
tic
%Study1 satistical behaviour
for i = 1:num_cases
[inputs ,fopt(i)] = ga(@stalagmite,2);
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
study1_time = toc
figure(1)
subplot(2,1,1)
hold on
surfc(xx,yy,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 Min')
tic
%Study2 satistical behaviour with upper and lower limits
for i = 1:num_cases
[inputs ,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6]);
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
study2_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('bounded inputs');
subplot(2,1,2)
plot(fopt)
xlabel('Iterations');
ylabel('Function Min')
tic
%Study2 satistical behaviour with upper and lower limits
options = optimoptions('ga');
options = optimoptions(options,'populationsize',180);
for i = 1:num_cases
[inputs ,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
study3_time = toc
figure(3)
subplot(2,1,1)
hold on
surfc(xx,yy,f)
shading interp
plot3(xopt,yopt,fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('bounded inputs');
subplot(2,1,2)
plot(fopt)
xlabel('Iterations');
ylabel('Function Min')
FUNCTION CODE
function z = stalagmite(input)
x = input(1);
y = input(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);
z = -(f1x*f1y*f2x*f2y);
OUTPUTS


