Week 4.1 - Genetic Algorithm
Aim-Write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.
General Theory
A stalagmite function generally refers to the function with which we are generating values over a stalagmite kind of surface for finding out the local and global maxima and minima of that particular given function. For this in MATLAB we are using a method called 'Optimization'.
Optimization an act, process, or methodology of making something (such as a design, system, or decision) as fully perfect, functional, or effective as possible specifically: the mathematical procedures (such as finding the maximum of a function) involved in this.
Optimization methods are used in many areas of study to find solutions that maximize or minimize some study parameters, such as minimize costs in the production of a good or service, maximize profits, minimize raw material in the development of a good, or maximize production.
Mathematical Expression for stalagmite function:

Here Writing a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.
%STALAGMITE FUNCTION
close all
clear all
clc
%Defining d array x and y
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
%Defining 2d Array of x & y using meshgrid command
[xx,yy]=meshgrid(x,y);
%solve stalagmite function
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_func(input_vector);
end
end
surfc(xx,yy,f)
xlabel('x value')
ylabel('y value')
shading interp
[x_inputs,fval]=ga(@stalagmite_func,2)
%%%%%%%%%%%%%% Function Call %%%%%%%%%%%%%
function [F]= stalagmite_func(input_vector)
x=input_vector(1);
y=input_vector(2);
f1=(sin(5.1*pi.*x+0.5)).^6;
f2=(sin(5.1*pi.*y+0.5)).^6;
f3=exp(-4*log(2).*((x-0.0667)^2/0.64));
f4=exp(-4*log(2).*((y-0.0667)^2/0.64));
F=(f1.*f2.*f3.*f4);
end
Code Explanation
- Here we take a two 1d row vector x and y with command linspace.
- using meshgrid command 1d array converted in to 2d array and store it in xx and yy.
- To solving stalagmite equation, for loop is used so that it run number of times equal to the length of 2d array.
- solving stalagmite equation we get value of equation.
- Surfc command used to plot 3D representation of x,y and stalagmite valuve which is seen in figure window.
- Here in 3D plot the we get the local maxima and global maxima.
- Shading interp command used to hide the grid lines on plot and gives plan stalagmite surface.
- ga is inbuild solver in matlab for optimize the function.
- ga solver always gives us the minimum value that is fval=0, mean at which values of input the function gives minima.
we have to optimize stalagmite function using genetic algorithm.
Introduction to Genetic Algorithms
A genetic algorithm is a search heuristic that is inspired by Charles Darwin’s theory of natural evolution. This algorithm reflects the process of natural selection where the fittest individuals are selected for reproduction in order to produce offspring of the next generation.

Notion of Natural selection
The process of natural selection starts with the selection of fittest individuals from a population. They produce offspring which inherit the characteristics of the parents and will be added to the next generation. If parents have better fitness, their offspring will be better than parents and have a better chance at surviving. This process keeps on iterating and at the end, a generation with the fittest individuals will be found.
This notion can be applied for a search problem. We consider a set of solutions for a problem and select the set of best ones out of them.
Five phases are considered in a genetic algorithm.
- Initial population
- Fitness function
- Selection
- Crossover
- Mutation
1)Initial population
The process begins with a set of individuals which is called a Population. Each individual is a solution to the problem you want to solve.
An individual is characterized by a set of parameters (variables) known as Genes. Genes are joined into a string to form a Chromosome (solution).In a genetic algorithm, the set of genes of an individual is represented using a string, in terms of an alphabet. Usually, binary values are used (string of 1s and 0s). We say that we encode the genes in a chromosome.

Population, Chromosomes and Genes
2)Fitness function
The fitness function determines how fit an individual is (the ability of an individual to compete with other individuals). It gives a fitness score to each individual. The probability that an individual will be selected for reproduction is based on its fitness score.
3)Selection
The idea of selection phase is to select the fittest individuals and let them pass their genes to the next generation.
Two pairs of individuals (parents) are selected based on their fitness scores. Individuals with high fitness have more chance to be selected for reproduction.
4)Crossover
Crossover is the most significant phase in a genetic algorithm. For each pair of parents to be mated, a crossover point is chosen at random from within the genes.
For example, consider the crossover point to be 3 as shown below.

Crossover point
Offspring are created by exchanging the genes of parents among themselves until the crossover point is reached.

The new offspring are added to the population.

New offspring
Mutation
In certain new offspring formed, some of their genes can be subjected to a mutation with a low random probability. This implies that some of the bits in the bit string can be flipped.

Mutation occurs to maintain diversity within the population and prevent premature convergence.
Termination
The algorithm terminates if the population has converged (does not produce offspring which are significantly different from the previous generation). Then it is said that the genetic algorithm has provided a set of solutions to our problem.
Comment
The population has a fixed size. As new generations are formed, individuals with least fitness die, providing space for new offspring.
The sequence of phases is repeated to produce individuals in each new generation which are better than the previous generation.
Code Structure
START
Generate the initial population
Compute fitness
REPEAT
Selection
Crossover
Mutation
Compute fitness
UNTIL population has converged
STOP
Find minimum of function using genetic algorithm
Syntax
x = ga(fun,nvars) finds a local unconstrained minimum, x, to the objective function, fun.nvars is the dimension (number of design variables) of fun.
x = ga(fun,nvars,A,b) finds a local minimum x to fun, subject to the linear inequalities A*x ≤ b. ga evaluates the matrix product A*x as if x is transposed (A*x').
x = ga(fun,nvars,A,b,Aeq,beq) finds a local minimum x to fun, subject to the linear equalities Aeq*x = beq and A*x ≤ b. (Set A=[] and b=[] if no linear inequalities exist.) ga evaluates the matrix product Aeq*x as if x is transposed (Aeq*x').
x = ga(fun,nvars,A,b,Aeq,beq,lb,ub) defines a set of lower and upper bounds on the design variables, x, so that a solution is found in the range lb ≤ x ≤ ub. (Set Aeq=[] and beq=[] if no linear equalities exist.)
x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon) subjects the minimization to the constraints defined in nonlcon. The function nonlcon accepts x and returns vectors C and Ceq, representing the nonlinear inequalities and equalities respectively. ga minimizes the fun such that C(x) ≤ 0 and Ceq(x) = 0. (Set lb=[] and ub=[] if no bounds exist.)
x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,options) minimizes with the default optimization parameters replaced by values in options. (Set nonlcon=[] if no nonlinear constraints exist.) Create options using optimoptions.
x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,intcon) OR
x =ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,intcon,options) requires that the variables listed in intcon take integer values.
x = ga(problem) finds the minimum for problem, a structure described in problem.
[x,fval] = ga(___) for any previous input arguments, also returns fval, the value of the fitness function at x.
[x,fval,exitflag,output] = ga(___) also returns exitflag, an integer identifying the reason the algorithm terminated, and output, a structure that contains output from each generation and other information about the performance of the algorithm.
[x,fval,exitflag,output,population,scores] = ga(___) also returns a matrix population, whose rows are the final population, and a vector scores, the scores of the final population.
Now we are writing code for 3 cases to find the optimum solution
%%%%%%%%%%%%%%%%%% GENETIC ALGORITHM STUDY %%%%%%%%%%%%%%%%%%
close all
clear all
clc
%Defining the array x and y using linspace command
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
%Defining 2d Array of x & y using meshgrid command
[xx,yy]=meshgrid(x,y);
tic %study time count start
%solve stalagmite function
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_func(input_vector);% calling stalagmite function
end
end
num_case=50; % run ga equal to 50 time
%%%%%%%%% CASE STUDY 1 %%%%%%%%%
for i=1:num_case
[inputs,fopt(i)]=ga(@stalagmite_func,2);% Ga function run for stalagmite function to generate optimum value
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
figure(1)
subplot(2,1,1)
surfc(xx,yy,f) % stalagmite function plot
shading interp %ungrid the plot(smooth representation)
hold on
plot3(xopt,yopt,fopt,'marker','o','markersize',6,'markerfacecolor','r')%plotting optimum values with randum
title('unbounded Inputs')
subplot(2,1,2)
plot(fopt)
xlabel('Iterations')
ylabel('function minimum')
study1_time=toc % study time count end
%%%%%%%% CASE STUDY 2 %%%%%%%
tic %study time count start
for i=1:num_case
[inputs,fopt(i)]=ga(@stalagmite_func,2,[],[],[],[],[0;0],[1;1]);% bounded inputs
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
figure(2)
subplot(2,1,1)
surfc(xx,yy,f)
shading interp
hold on
plot3(xopt,yopt,fopt,'marker','o','markersize',6,'markerfacecolor','r')
title('Bounded inputs')
subplot(2,1,2)
plot(fopt)
xlabel('Iterations')
ylabel('function minimum')
study2_time=toc% study time count end
%%%%%%%% CASE STUDY 3 %%%%%%%
options = optimoptions('ga')
options = optimoptions(options,'populationSize',200)%population size increased
tic %study time count start
for i=1:num_case
[inputs,fopt(i)]=ga(@stalagmite_func,2,[],[],[],[],[0;0],[1;1],[],[],options);
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
figure(3)
subplot(2,1,1)
surfc(xx,yy,f)
shading interp
hold on
plot3(xopt,yopt,fopt,'marker','o','markersize',6,'markerfacecolor','r')
title('Bounded Inputs with modified population')
subplot(2,1,2)
plot(fopt)
xlabel('Iterations')
ylabel('function minimum')
study3_time=toc% study time count end
%%%%%%%% Function %%%%%%%%%%%
function [F]= stalagmite_func(input_vector)
x=input_vector(1);
y=input_vector(2);
f1=(sin(5.1*pi.*x+0.5)).^6;
f2=(sin(5.1*pi.*y+0.5)).^6;
f3=exp(-4*log(2).*((x-0.0667)^2/0.64));
f4=exp(-4*log(2).*((y-0.0667)^2/0.64));
F=-(f1.*f2.*f3.*f4);
end
%% GA function always give us minimum function value
% so that we use -Ve sign here to find maxima
Errors Occure while Coding Ga
Error 1

Here in stalagmite function I missing to write multiplication operator
f3=exp(-4*log(2).*((x-0.0667)^2/0.64));
so write multiplication sign an error solved.
Error 2

Here I am not write the nested loop for stalagmite function properly so that this error occure
write the proper code to solve the error.
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_func(input_vector);
end
end
Results of Ga optimisation
Study 1

Above figure shows that the Ga find the maxima outside the givin inputs that is optimisation is unbounded .
we can not find the optimum value of function.
Using tic & toc command optimisation time is evaluted and it is 2.2361 sec
Study 2

Above figure shows the results of study 2. Herewe bounded inputs so that getting better result than the study 1 .It is more clear that the where our maxima .
case study 3

In this case the modified the search space for GA .Population size increase from 150 to 200.
The result of optimisation is more accurate than study 2.But it requred more optimisation time as compaire to above two cases .
Thus it shows that in this case bounded inputs and the increase in population size gives more clear results of optimisation.
Referances
https://www.sciencedirect.com/topics/engineering/genetic-algorithm.
https://in.mathworks.com/help/gads/what-is-the-genetic-algorithm.html
https://en.wikipedia.org/wiki/Genetic_algorithm
https://link.springer.com/article/10.1007/s11042-020-10139-6