Week 4.1 - Genetic Algorithm
clear
close
clc
% Defining the range of search
x=linspace(0,0.6,150)
y=linspace(0,0.6,150)
[xx yy]=meshgrid(x,y)
%% To find the global maxima using genetic algo, multiply stalagmite function with -1
%% and find the global minima
% Evaluating stalgamite function
for i=1:1:150
for j=1:1:150
input_vector(1)=xx(i,j);
input_vector(2)=yy(i,j)
f(i,j)=stalagmite(input_vector);
end
end
%%plotting the function on subplot
figure(1)
subplot(2,1,1)
surfc(xx,yy,f)
shading interp
hold on
%% Study 1: Genetic algorithm without bounds
iterations=50
for i=1:1:iterations
[results,fval]=ga(@stalagmite,2)
x1(i)=results(1)
y1(i)=results(2)
z1(i)=fval
end
plot3(x1,y1,z1)
title("GA without bounds")
plot3(x1,y1,z1,"*")
hold off
subplot(2,1,2)
plot(z1)
title('Iterations vs Function minima')
xlabel("Iterations")
ylabel("Fmin")
%% Study 2:Genetic algorithm with bounds
for i=1:1:iterations
[results,fval]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6])
x2(i)=results(1)
y2(i)=results(2)
z2(i)=fval
end
figure(2)
subplot(2,1,1)
surfc(xx,yy,f)
shading interp
hold on
plot3(x2,y2,z2)
title("GA with bounds")
plot3(x2,y2,z2,"*")
subplot(2,1,2)
plot(z2)
title('Iterations vs Function minima')
xlabel("Iterations")
ylabel("Fmin")
%%Study 3 increasing the genetic algo iterations
options=optimoptions('ga');
options=optimoptions(options,'PopulationSize',170)
for i=1:1:iterations
[results,fval]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6])
x3(i)=results(1)
y3(i)=results(2)
z3(i)=fval
end
figure(3)
subplot(2,1,1)
surfc(xx,yy,f)
shading interp
hold on
plot3(x3,y3,z3)
title("GA with bounds & Increased iterations ")
plot3(x3,y3,z3,"*")
subplot(2,1,2)
plot(z3)
title('Iterations vs Function minima')
xlabel("Iterations")
ylabel("Fmin")
%% To Find the global minima we find the lowest of Local Minimas
f_min=z3(1)
Min_input=[x3(1) y3(1)];
for i=2:1:iterations
if z3(i)<f_min
f_min=z3(i);
Min_input=[x3(i) y3(i)];
end
end
disp(Min_input)
disp(f_min)