Week 5 - Genetic Algorithm
close all
clear all
clc
%input
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
num_spaces=50;
%forming 2d array
[xx,yy]=meshgrid(x,y);
for i=1:length(x)
for j=1:length(y)
input_vector(1)=xx(i,j);
input_vector(2)=yy(i,j);
f(i,j)=stagalmite(input_vector);
end
end
%study 1-unbounded
tic
for i=1:num_spaces
[results,fopt(i)]=ga(@stagalmite,2)
xopt(i)=results(1)
yopt(i)=results(2)
end
study_time1=toc
figure(1)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
%study 2- bounded
tic
for i=1:num_spaces
[results,fopt(i)]=ga(@stagalmite,2,[],[],[],[],[0;0],[0.6;0.6])
xopt(i)=results(1)
yopt(i)=results(2)
end
study_time2=toc
figure(2)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
%study3- increased initial population
tic
options=optimoptions('ga')
options=optimoptions(options,'populationsize',250)
for i=1:num_spaces
[results,fopt(i)]=ga(@stagalmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options)
xopt(i)=results(1)
yopt(i)=results(2)
end
study_time3=toc
figure(3)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')