Week 4.1 - Genetic Algorithm
Write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.
clear all
close all
clc
%Definng our our search space
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
%Creating a 2Dimentional 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
%Converting Fitting function to change the graph upwards
F=-f;
%Plotting Stalagmite Function
surface(xx,yy,F);
%Shading interp;
hold on;
%Perfoming the genetic algorithm
[output,fval]=ga(@stalagmite,2,[],[],[],[],[0,0],[0,6,0.6])
%Plotting global maxima
x_max=output(:,1);
y_max=output(:,2);
f_max=-fval;
plot3(x_max,y_max,'marker','o','markersize',5,'markerfacecolor','r');
xlabel('X-value');
ylabel('Y-value')
title('Global Maxima');
legend('STALAGMITE','GLOBAL MAXIMA')
Clearly expalin the concept of genetic algorithm in your own words and also explain the syntax for ga in MATLAB in your report
Genitic algorithm
-Inspired by Charles Darwin's theory of natural selection
-The algorithm reflects the process of natural selection where the fittest individual is selected for reproduction in order to produce offspring of the next generation.
In computer science ,operations research , a genetic algorith are commonly used to generate high-quality solutions to optimisation and search problems .


Governing equations
`f_1(x)=[sin(5.1*pi*x+0.5)]^6`
`f_1(y)=[sin(5.1*pi*y+0.5)]^6`
`f_2(x)=(e^(-4*log2*(x-0.0667)^2 ))/0.64`
`f_2(y)=(e^(-4*log2*(y-0.0667)^2 ))/0.64`
`f(x,y)=f_1(x)*f_1(y)*f_2(x)*f_2(y)`
Maximising f(x,y) is the same as minimising -f(x,y)
ga syntax
X=ga(fun,nvars,A,b,beq,lb,ub)
-first syntax gives ga takes inputs as fitting equation
-Second syntax provides bounds to ga
-Third syntax gives value for x as well as functiom minimum value.

Output


Statistical Behavior
% Statistical Behaviour
clear all
close all
clc
% Defining our Search Space
X=linspace (0,0.6,150);
y=linspace(0,0.6,150);
num_case = 50;
% Creating 2-d Array
[xx,yy] = meshgrid(x,y)
% Calculating Fitting 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_func (input);
end
end
% Converting Fitting Function to change the graph upwards
F = -f;
% Performing the Genetic Algorithm
tic
for k=1:num_case
[inputs, fopt (k)] = ga(@stalagmite_func,2);
xopt (k) = inputs(1);
yopt (k) = inputs(2);
end
study_time=toc
% Plotting Global Maxima And Function Values
figure(1)
subplot(2,1,1)
hold on
surfc(x,y,F)
shading interp
plot3(xopt, yopt, -fopt, 'marker', 'o', 'markersize',5, 'markerfacecolor', 'r');
xlabel ('X-value');
ylabel ('y-value');
title('Unbounded Inputs');
legend('STALAGMITE', 'GLOBAL MAXIMA')
subplot(2,1,2)
hold on
plot (fopt)
xlabel ('Iterations');
ylabel ('Function Maxima');
title('Variation in F'); legend('Change in F value')
Results

