All Courses
All Courses
Courses by Software
Courses by Semester
Courses by Domain
Tool-focused Courses
Machine learning
POPULAR COURSES
Success Stories
AIM To write a code in MATLAB to optimize the stalagmite function and find the global maxima of the function. INTRODUCTION 1. OPTIMIZATION TECHNIQUES: Mathematical optimization (alternatively spelled optimization) or mathematical programming is the selection of a best element (with regard…
Laasya Priya Nidamarty
updated on 12 Feb 2021
To write a code in MATLAB to optimize the stalagmite function and find the global maxima of the function.
Mathematical optimization (alternatively spelled optimization) or mathematical programming is the selection of a best element (with regard to some criterion) from some set of available alternatives. In the simplest case, an optimization problem consists of maximizing or minimizing a real function by systematically choosing input values from within an allowed set and computing the value of the function. The generalization of optimization theory and techniques to other formulations constitutes a large area of applied mathematics. More generally, optimization includes finding "best available" values of some objective function given a defined domain (or input), including a variety of different types of objective functions and different types of domains. [1]
The classical optimization techniques are useful in finding the optimum solution or unconstrained maxima or minima of continuous and differentiable functions. The optimization techniques are the analytical methods, and they make use of differential calculus in locating the optimum solution. The classical methods have limited scope in practical applications as some of them involve objective functions which are not continuous and/or differentiable. Yet, the study of these classical techniques of optimization forms a basis for developing most of the numerical techniques that have evolved into advanced techniques more suitable to current practical problems. These optimization methods assume that the function is differentiable twice with respect to the design variables and the derivatives are continuous.
Three main types of problems that can be handled by the classical optimization techniques:
The numerical methods of optimization are discussed below: [2]
The advanced optimization techniques are discussed below: [2]
In computer science and operations research, a genetic algorithm (GA) is a metaheuristic inspired by the process of natural selection that belongs to the larger class of evolutionary algorithms (EA). Genetic algorithms are commonly used to generate high-quality solutions to optimization and search problems by relying on biologically inspired operators such as mutation, crossover, and selection. In a genetic algorithm, a population of candidate solutions (called individuals, creatures, or phenotypes) to an optimization problem is evolved toward better solutions. Each candidate solution has a set of properties (its chromosomes or genotype) which can be mutated and altered; traditionally, solutions are represented in binary as strings of 0s and 1s, but other encodings are also possible. The evolution usually starts from a population of randomly generated individuals, and is an iterative process, with the population in each iteration called a generation. In each generation, the fitness of every individual in the population is evaluated; the fitness is usually the value of the objective function in the optimization problem being solved. The more fit individuals are stochastically selected from the current population, and each individual's genome is modified (recombined and possibly randomly mutated) to form a new generation. The new generation of candidate solutions is then used in the next iteration of the algorithm. Commonly, the algorithm terminates when either a maximum number of generations has been produced, or a satisfactory fitness level has been reached for the population.
A typical genetic algorithm requires:
A standard representation of each candidate solution is as an array of bits. Arrays of other types and structures can be used in essentially the same way. The main property that makes these genetic representations convenient is that their parts are easily aligned due to their fixed size, which facilitates simple crossover operations. Variable length representations may also be used, but crossover implementation is more complex in this case. Tree-like representations are explored in genetic programming and graph-form representations are explored in evolutionary programming; a mix of both linear chromosomes and trees is explored in gene expression programming. Once the genetic representation and the fitness function are defined, a GA proceeds to initialize a population of solutions and then to improve it through repetitive application of the mutation, crossover, inversion, and selection operators. [3]
The five phases that are considered in a genetic algorithm are described as follows:[4]
Figure 1. Depiction of Gene, Chromosome and Population
For example, consider the crossover point to be 3 as shown below in the figure 2.
Figure 2. Showing Crossover point
The offspring are created by exchanging the genes of parents among themselves until the crossover point is reached.
Figure 3. Process of crossover
The new offspring are added to the population as shown below:
Figure 4. Offspring
Figure 5. Offspring before and after mutation
A stalagmite function defined by the following set of equations:
A code using the above set of equations is to be written to evaluate the Global maxima.
%Program to evaluate the global maxima
clear all
close all
clc
%Defining the search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
%creating 2D mesh
[xx,yy] = meshgrid(x,y);
%defining the number of times to run the genetic algorithm
p = 50;
%EVALUATION USING BASIC FITNESS FUNCTION
tic
%Evaluating stalgamite 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(input_vector);
end
end
for i = 1:p
[inputs,fopt(i)] = ga(@stalagmite,2);
xopt(i) = inputs(1);
yopt(i) = inputs(1);
end
study1_time = toc;
figure(1);
subplot(2,1,1);
hold on;
surfc(xx,yy,-f);
shading interp;
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','k');
legend('stalagmite','stalgamite','Global maxima')
xlabel('X-values');
ylabel('Y-values');
zlabel('Z-Values');
title('Unbounded Inputs');
subplot(2,1,2);
plot(-fopt);
legend('Optimized f value');
xlabel('Iterations');
ylabel('Function Fitness');
%EVALUATION USING ADDITIONAL PARAMETERS - setting the boundaries
tic
for i = 1:p
[inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
xopt(i) = inputs(1);
yopt(i) = inputs(1);
end
study2_time = toc;
figure(2);
subplot(2,1,1);
hold on;
surfc(xx,yy,-f);
shading interp;
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','k');
legend('stalagmite','stalgamite','Global maxima')
title('Bounded Inputs');
xlabel('X-values');
ylabel('Y-values');
zlabel('Z-Values');
subplot(2,1,2);
plot(-fopt);
legend('Optimized f value');
xlabel('Iterations');
ylabel('Function Fitness');
%EVALUATION USING ADDITIONAL PARAMETERS - varying population
options = optimoptions('ga');
options = optimoptions(options,'PopulationSize',100);
tic
for i = 1:p
[inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],options);
xopt(i) = inputs(1);
yopt(i) = inputs(1);
end
study3_time = toc;
figure(3);
subplot(2,1,1);
hold on;
surfc(xx,yy,-f);
shading interp;
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','k');
legend('stalagmite','stalgamite','Global maxima')
title('Bounded Inputs with defined Popoulation');
xlabel('X-values');
ylabel('Y-values');
zlabel('Z-Values');
subplot(2,1,2);
plot(-fopt);
legend('Optimized f value');
xlabel('Iterations');
ylabel('Function Fitness');
EXPLANATION:
EVALUATION USING BASIC FITNESS FUNCTION
function [z] = stalagmite(input_vector)
x = input_vector(1);
y = input_vector(2);
f_1x = (sin(5.1*pi*x + 0.5))^6;
f_1y = (sin(5.1*pi*y + 0.5))^6;
f_2x = exp(-4*log(2)*((x-0.0667)^2/0.64));
f_2y = exp(-4*log(2)*((y-0.0667)^2/0.64));
[z] = -[f_1x*f_2x*f_1y*f_2y];
end
DESCRIPTION:
In this, a matrix [z] is assigned to a function stalagmite which takes a single input named ‘input_vector’.
The input_vector(1) is assigned to x value and input_vector(2) is assigned to y value. The stalagmite function is defined using f_1x, f_1y, f_2x and f_2y as mentioned in problem statement. At last, the value of [z] is defined by the negative product of the values of the function f along x and y directions. The incorporation of the negative sign is because, genetic algorithm by default, calculates the global minima and here, in the current study, global maxima is needed. Therefore, the sign variation mathematically sums up to the value being global maxima.
Selecting two loop counter variables I and j which run from 1 to the length of xx and yy respectively. The values of xx(i,j) and yy(i,j) are assigned to input_vector(1) and input_vector(2) respectively. Then stalagmite function is invoked to be assigned to f(i,j). It is made sure that the dimensions are intact.
A for loop is established that ranges from 1 to 50 (i.e. number of times the genetic algorithm was intended to run which is defined as ‘p’ in the inputs). An array consisting of inputs and optimum function value is considered and genetic algorithm that runs on stalagmite is assigned to this array as shown below:
[inputs,fopt(i)] = ga(@stalagmite,2);
In this, we observe the command ‘ga’ that stands for genetic algorithm.
COMMAND ‘ga’ : Genetic algorithm solver for mixed-integer or continuous-variable optimization, constrained or unconstrained. Genetic algorithm solves smooth or nonsmooth optimization problems with any types of constraints, including integer constraints. It is a stochastic, population-based algorithm that searches randomly by mutation and crossover among population members
.
Syntax: x = ga(fun,nvars)
This finds a local unconstrained minimum, x, to the objective function, fun. nvars is the dimension (number of design variables) of fun. [6]
Therefore, in the written code, to evaluate the optimum value for the input, the genetic algorithm takes in a function handle that holds the function to be evaluated i.e., stalagmite function and also the number of variables that are a part of the function ‘stalagmite’ which in this case are two i.e., x and y.
COMMANDS TIC AND TOC: The command ‘tic’ works with the ‘toc’ function to measure elapsed time. The tic function records the current time, and the toc function uses the recorded value to calculate the elapsed time. [7]
SUBPLOT COMMAND: subplot(m,n,p) divides the current figure into an m-by-n grid and creates axes in the position specified by p. MATLAB® numbers subplot positions by row. The first subplot is the first column of the first row, the second subplot is the second column of the first row, and so on. If axes exist in the specified position, then this command makes the axes the current axes. [8]
SURFACE CONTOUR COMMAD: surfc(X,Y,Z) creates a three-dimensional surface plot with a contour plot underneath. A surface plot is a three-dimensional surface that has solid edge colors and solid face colors. The function plots the values in matrix Z as heights above a grid in the x-y plane defined by X and Y. The color of the surface varies according to the heights specified by Z. [9]
SHADING INTERP: shading interp varies the color in each line segment and face by interpolating the colormap index or true color value across the line or face. [10]
PLOT3 COMMAND: plot3(X, Y, Z) plots coordinates in 3-D space. To plot a set of coordinates connected by line segments, specify X, Y, and Z as vectors of the same length. To plot multiple sets of coordinates on the same set of axes, specify at least one of X, Y, or Z as a matrix and the others as vectors. [11]
OBSERVATION AND CONCLUSION:
X : 0.681514
Y: 0.681514
Z: 0.994995
Figure 6. Results of basic fitness using genetic algorithm.
EVALUATION USING ADDITIONAL PARAMETERS - setting the boundaries:
A for loop is established that ranges from 1 to 50 (i.e. number of times the genetic algorithm was intended to run which is defined as ‘p’ in the inputs). An array consisting of inputs and optimum function value is considered and genetic algorithm that runs on stalagmite is assigned to this array as shown below:
[inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
In this, we observe the command ‘ga’ that stands for genetic algorithm, has a different syntax from the one that was used to execute the optimization in the case mentioned before. The syntax for ga is explained as below:
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.) [6]
OBSERVATION AND CONCLUSION:
Figure 7. Results of bounded inputs using genetic algorithm.
X : 0.0668267
Y: 0.0668267
Z: 1
EVALUATION USING ADDITIONAL PARAMETERS - varying population along with defined boundaries.
A for loop is established that ranges from 1 to 50 (i.e. number of times the genetic algorithm was intended to run which is defined as ‘p’ in the inputs). An array consisting of inputs and optimum function value is considered and genetic algorithm that runs on stalagmite is assigned to this array as shown below:
[inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],options);
In this, we observe the command ‘ga’ that stands for genetic algorithm, has a different syntax from the one that was used to execute the optimization in the case mentioned before. This not only includes the boundaries but also includes the options that are used to guide the execution of ‘ga’. The syntax for ga is explained as below:
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.) (Set Aeq=[] and beq=[] if no linear equalities exist.) Create options using optimoptions. [6]
OPTIMOPTIONS COMMAND: It is used to create optimization options.
options = optimoptions(SolverName) returns a set of default options for the SolverName solver.
options = optimoptions(oldoptions,Name,Value) returns a copy of oldoptions with the named parameters altered with the specified values. [12]
OBSERVATION AND CONCLUSION:
X : 0.066842
Y: 0.066842
Z: 1
Figure 8. Results of bounded inputs with defined population using genetic algorithm.
Population Size |
X- Value |
Y- Value |
Z- Value |
Time taken (seconds) |
100 |
0.0668368 |
0.0668368 |
1 |
4.1511 |
150 |
0.0668285 |
0.0668285 |
1 |
5.5437 |
200 |
0.0668249 |
0.0668249 |
1 |
7.2886 |
250 |
0.0668319 |
0.0668319 |
1 |
8.6755 |
300 |
0.0668424 |
0.0668424 |
1 |
10.2600 |
350 |
0.0668414 |
0.0668414 |
1 |
11.9839 |
400 |
0.0668298 |
0.0668298 |
1 |
14.8394 |
Table 1. Tabulation of results obtained by varying population size.
In 1895, Charles Darwin proposed a theory of natural selection that emphasized on the carrying of the desired characteristic traits of one generation to their offspring. This detailed about a species’ adaption to the environment that it is subjected to and passing down the necessary and important information of survival to the next generation.
Charles Darwin defined natural selection as the "principle by which each slight variation [of a trait], if useful, is preserved" [6]
Based on this theory, genetic algorithm is formulated, that performs optimization of the population. A certain set of population is considered and is subjected to calculate the fitness. This procedure identifies the heritable traits of the population over the regular traits. If any appreciable phenotype is observed from the population under consideration it is processed further, otherwise the process of mutation is terminated. Once the desired traits are observed, the selection of such population is carried on and is subjected to crossover. This process is analogous to reproduction in biological terms. Off-springs with desired traits are obtained. Among the produced off-springs, few of them undergo mutation i.e. development in their traits to stand a better chance for selection. The mutated species are again subjected to fitness calculation. The process is iterative until there is no chance of generating an heir or until all the possibilities of the mutations are exhausted and the domain converges into a single point.
Figure 6. Flowchart of Genetic Algorithm
MATLAB gives the user to evaluate the genetic algorithm using different syntaxes based on the availability of the information with the user. It helps to optimize the function accordingly thereby helping the user find the global minima. The following are the syntaxes used to evaluate the genetic algorithm:
Description |
X-Value |
Y-Value |
Z-Value |
Time (sec) |
Only function and number of variables are invoked in ‘ga’ |
0.681514 |
0.681514 |
0.994995 |
2.1724 |
Boundaries are also invoked in ‘ga’
|
0.0668267 |
0.0668267 |
1 |
2.5177 |
Boundaries along with population size are invoked in ‘ga’ |
0.0668424 |
0.0668424 |
1 |
10.2600 |
In conclusion, the genetic algorithm is one of the finest ways to perform the optimization of the function under consideration. The efficiency of the genetic algorithm can also be improved by using additional parameters. In this method the anonymous function is used to capture the values of additional arguments, namely the constants. And further assigning this to the known function and evaluating it by defining the constant values will reduce the computational time. To further reduce the computational time when large amounts of information is being subjected to optimization, vectorized parameter method can be adopted. The parameters in this method are converted into vectors.
Leave a comment
Thanks for choosing to leave a comment. Please keep in mind that all the comments are moderated as per our comment policy, and your email will not be published for privacy reasons. Please leave a personal & meaningful conversation.
Other comments...
Week 1 Understanding Different Battery Chemistry
AIM To understand different battery chemistry. INTRODUCTION 1. ELECTRIC SCOOTER/VEHICLE: [1] Electric motorcycles and scooters are plug-in electric vehicles with two or three wheels. The electricity is stored on board in a rechargeable battery, which drives one or more electric motors.…
02 Jun 2021 02:33 PM IST
Final Project: Design of an Electric Vehicle
AIM To create a Simulink model of an EV. INTRODUCTION OF ELECTRIC VEHICLES: INTRODUCTION OF ELECTRIC VEHICLES: Electric vehicles (EVs) use an electric motor for traction, and chemical batteries, fuel cells, ultracapacitors, and/or flywheels for their corresponding energy sources. The electric vehicle has many advantages…
26 May 2021 04:11 PM IST
Project-1: Powertrain for aircraft in runways
AIM To understand powertrain for aircraft in runways. PROBLEM SPECIFICATION AND SOLVING: PROBLEM STATEMENT I: Search and list out the total weight of various types of aircrafts. EXPLANATION AND OBSERVATION: [1] There are many factors that lead to efficient and safe operation of aircraft. Among these vital factors are proper…
17 May 2021 11:24 AM IST
Week-11 Challenge: Braking
AIM To understand Braking in automobiles. INTRODUCTION 1. BRAKE: [1] Brake is a mechanical device that inhibits motion by absorbing energy from a moving system. It is used for slowing or stopping a moving vehicle, wheel, axle, or to prevent its motion, most often accomplished by means…
06 May 2021 11:48 AM IST
Related Courses
Skill-Lync offers industry relevant advanced engineering courses for engineering students by partnering with industry experts.
© 2025 Skill-Lync Inc. All Rights Reserved.