Week 4.1 - Genetic Algorithm
Program to optimize the stalagmite function and to find global maxima
Program Code:
clear all
close all
clc
% Defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
%creating 2 dimensional mesh
[xx yy] = meshgrid(x,y);
% Evaluating the stalagmite function
for i=1:length(xx)
for j=1:length(yy)
input(1)=xx(i,j);
input(2)=yy(i,j);
f(i,j)=stalagmite(input);
end
end
num_cases=50;
%study 1 unbounded limits
for i= 1:num_cases
[inputs,fval(i)] = ga(@stalagmite,2);
x1(i) = inputs(1);
y1(i) = inputs(2);
end
figure(1)
subplot(2,1,1)
surfc(xx,yy,-f)
xlabel('x value')
ylabel('y value')
shading interp
hold on
plot3(x1,y1,-fval,'marker','o','markerSize',3,'MarkerFaceColor','r')
title('Unbounded limits')
subplot(2,1,2)
plot(fval)
xlabel('Iteration')
ylabel('Function')
%study 2 bounded limits
for i= 1:num_cases
[inputs,fval2(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6]);
x2(i) = inputs(1);
y2(i) = inputs(2);
end
figure(2)
subplot(2,1,1)
surfc(xx,yy,-f)
xlabel('x value')
ylabel('y value')
shading interp
hold on
plot3(x2,y2,-fval2,'marker','o','markerSize',3,'MarkerFaceColor','r')
title('Bounded limits')
subplot(2,1,2)
plot(fval2)
xlabel('iteration')
ylabel('function')
%study3 - increasing ga iteration
options = optimoptions('ga');
options = optimoptions(options,'PopulationSize',170);
tic
for i= 1:num_cases
[inputs,fval3(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
x3(i) = inputs(1);
y3(i) = inputs(2);
end
study3_time = toc
figure(3)
subplot(2,1,1)
surfc(xx,yy,-f)
xlabel('x value')
ylabel('y value')
shading interp
hold on
plot3(x3,y3,-fval3,'marker','o','markerSize',3,'MarkerFaceColor','r')
title('More Optimization')
subplot(2,1,2)
plot(fval3)
xlabel('Iteration')
ylabel('Function')
Function Code:
function [f] = stalagmite(input)
x = input(1);
y = input(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.0667)^2)/0.64));
f2_y=exp(-4*log(2)*(((y-0.0667)^2)/0.64));
f = -(f1_x*f1_y*f2_x*f2_y);
end
ga(genetic algorithm) Defines:
ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
- @stalagmite - its the function file for optimization
- 2 - it denotes the no. of variables that has been used
- [] - A - linear equality constraints
- [] - B - linear equality constraints
- [] - Aeq - linear equality constraints
- [] - Beq - linear equality constraints
- [0;0] - lb(lower bounds) - it denotes the limits
- [0.6;0.6] - ub(upper bounds) - it denotes the limits
- [] - nonlcon(nonlinearity constraints)
- Options - it denotes the size of the population for optimization.
Output:
1. Case Study 1 - Unbounded limits:

2. Case Study 2 - Bounded limits - upper bounds and lower bounds:

3. Case Study 3 - Optimized Parameter:
