Project

Genetic Algorithm - Calculation of the Global Maxima of a Stalagmite Function

Week 4 : Genetic Algorithm

  • Write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.
  • Clearly explain the concept of genetic algorithm in your own words and also explain the syntax for ga in MATLAB in your report.
  • Make sure that your code gives the same output, even if it is made to run several times.
  • Plot graphs for all 3 studies and for F maximum vs no. of iterations. Title and axes labels are a must, legends could be shown if necessary.

ANS:

Theory

A genetic algorithm is a a method of optimization in order to determine the global minima of a function via an interative search. This method has the word \'genetic\' in its name because the process uses Darwin\'s theory of evolution as an analogy in its optimization procedure. The algorithm is inspired by Darwin\'s theory of evolution which was based on the idea of natural selection. Natural selection says that members of a population which had \'suitable\' characteristics (genes) would be able to survive their environment and subsequently reproduce to create the next generation of members. This new generation would inherit the characteristics i.e. genes that their parents had (which allowed them to survive) and therefore, would be fit to continue surviving. This process continues on for many generations resulting in a population with inherited genes that nature deems is fit for suvival. Hence, Darwin coined the phrase \'Survival of the fittest\'.

Outline of Genetic Algorithm Process

1. Initial Population

The process begins with an initial population or sample. Each member in the sample is a solution to the problem we want to solve. This population is generated by creating a sample space which is a range of suitable solutions to the function we want to solve for.

2. Fitness Function

A fitness function is a function used to determine how fit each member is via a fitness score. The level of fitness measures its ability to \'compete\' with the other members. The next phase is \'selection\' where the fittest members are selected based on the fitness score. 2 pairs of individuals (parents) are selected at a time. The higher the fitness score, the greater the probability that the member is chosen to carry on to the next generation/iteration. If the fitness score is not optimal enough for certain individuals, they are eliminated from the population. The surviving ones proceed to the next stages.

3. Crossover

In this phase, the genes of pairs of fit individuals are combined to create the children for the next generation. The crossover point is the point until the genes of the parents are exchanged to create the children. The children are now the new members for the next generation.

4. Mutation

In some cases, the genes of the parents undergo a random change and this creates diversity among their children. This prevents premature convergence also so that the children are as different from one another as possible.

5. New Population

The children/offspring of the new generation are now the new population sample to consider. Now, they will be run through the fitness function to determine their fitness scores and to decide whether or not they are fit enough to survive to the next generation. This process continues as a loop for however many iterations we specify.

6. Termination

As the iterations go on, the popultion will \'evolve\' to an optimal solution. This means that the population will result in individuals having the best characteristics for the solution to the function. The algorithm stops or \'terminates\' if the population converged to create offspring which are not significantly different from the previous generation. The algorithm can also \'terminate\' if the number of iterations specified has been reached.

Genetic Algorithm Syntax

Below are the different forms for the syntax of the genetic algorithm solver:

x = ga(fn, 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 equalities A*x≤b. ga evaluates the matrix product A*x as if x is transposed to (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 marix 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 A = [] and b = [] if no linear inequalities 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 = [] is no bounds exist.)

x = ga(fun, nvars, A, b, Aeq, beq, lb, ub, nonlcon, options) - minimizes 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) - requires that the variables listed in IntCon take integer values

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, where problem is a structure.

[x, fval] = ga(__) - for any previous 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.

Program

First, I will have written the program for the stalagmite function. The stalagmite function is shown below:

`f(x,y) = f_1,_x*f_2,_x*f_1,_y*f_2,_y`

Each component in the function has its own function:

`f_1,_x = [sin(5.1pix + 0.5)]^6`

`f_1,_y = [sin(5.1piy + 0.5)]^6`

`f_2,_x = exp[-4ln(2)*(x-0.0667)^2/0.64]`

`f_2,_y = exp[-4ln(2)*(y-0.0667)^2/0.64]`

The stalagmite function will be our fitness function.

The 4 components of the stalagmite function and the stalagmite function itself is coded for in the below section of code. This section is saved as a separate script with the filename being the same as the function name. So the script is saved as \'stalagmite.m\'.

function [F] = 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.00667).^2/0.64);
f_2y = exp((-4*log(2))*(y-0.00667).^2/0.64);

F = -(f_1x*f_1y*f_2x*f_2y);

end

As you can see, the first line is the creation of the function. The function name is \'stalagmite\' and the parentheses after it shows the input variables it needs called the \'input_vector\'. Since the stalagmite function contains 2 variables (x and y), it needs 2 inputs for each. So, in the next 2 lines, variables \'input_vector(1)\' and \'input_vector(2)\' are created and assigned to x and y.

The output of the function will be stored in the variable, \'F\'.

The next 4 lines show the 4 components of the stalagmite function coded so that each component can be calculated separately first. In the final line, the 4 components are multiplied together and the product of this calculation is equated to the variable \'F\'.

A negative sign is inserted in the start of the equation because we are required to find the global maxima of the stalagmite function. Ordinarily, the genetic algorithm will find the minimum value of a function. So by putting a negative sign, we are going to be finding the maximum value of the function instead since the minimum of -f(x) is the maximum of f(x).

Main Code

clear all
close all
clc

% Defining the search space 

x = linspace (0, 0.6, 150);
y = linspace (0, 0.6, 150);
cases = 50;


% Creating a 2D mesh
[xx, yy] = meshgrid (x, y);

The first 3 lines show the commands clear all, close all and clc which reset all variables and parameters preset in MATLAB from any previous coding sessions.

In the next 2 lines of code, the search space for the genetic algorithm is defined using the \'linspace\' command. The search space is created for 2 variables x and y between 0 and 0.6 with 150 increments.

Then the number of iterations that we want to run the genetic algorithm for is defined under the variable name \'cases\' and it has been equated to 50. So, this algorithm will run for 50 times and come to a stop i.e. termination.

In the last line, a 2D mesh grid is created using the \'meshgrid\' command with the variables x and y defined from the search space.

%% Evaluating the 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(input_vector);
    
    end
end

In this next section of code, a for loop is created for evaluating the stalagmite function. The first line specifies for how many loops the for loop should run for. In this case, the for loop should run starting from 1 till the length of the array, \'xx\' using the counter \'i\'. Similarly a nested loop is created for the next line for the same purpose and this runs from 1 till the length of the array, \'yy\'.

The arrays \'xx\' and \'yy\' are basically 150x150 matrices containing the values defined from the search space.

This for loop is needed to input values in to the stalagmite function. The for loop will keep inputting the values from the arrays \'xx\' and \'yy\' into the stalagmite function.

The third line shows that the first value for calculation should be taken from the \'xx\' array from position (i,j) and be assigned to the variable, \'input_vector(1)\'. This variable represents the x variable in the stalagmite function.

The fourth line shows the same but with respect to the y variable in the stalagmite function. The y value is taken from the \'yy\' array from position (i.j) and assigned to the variable \'input_vector(2)\'.

For instance, when the \'i\' and \'j\' counter are both 1, the coordinates for (i,j) will be (1,1).

So the value from first row and first column of \'xx\' and \'yy\' arrays will be taken which will be (0,0).

So, \'input_vector(1)\' will be equal to 0 and \'input_vector(2)\' will be equal to 0.

Then in the last line, we are calling the stalagmite function and the 2 values for x and y will be the inputs to the function.

Case 1 - Statistical Behaviour of Genetic Algorithm

In this section of code, we will investigate the statistical behavior of the genetic algorithm.

%% 1st case - Statistical Behaviour

tic

for i = 1 : cases
    [inputs, fopt(i)] = ga(@stalagmite, 2);
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
    
end

case1_time = toc

F = -f;
Fopt = -fopt;

The first line shows the \'tic\' command starts a timer to measure the time taken to execute code. This is measured until the command, \'toc\' is seen. The \'toc\' command is assigned to the variable, \'case1_time\'.

Then, a for loop is created which will loop using the counter \'i\' and will range from 1 till the number of cases, previously defined as 50. This for loop calls the stalagmite function using the \'@\' operator. The simplest syntax for the genetic algorithm is: x = ga(fun, nvars), where \'fun\' is the fitness function (which is the stalagmite function) and \'nvars\' represents the number of variables our fitness function has. This syntax is used when we are trying to find a local unconstrained global minima (or maxima). In this case, we are not using any constraints i.e. bounds to limit the value that the maxima can take.

The \'ga\' function is used which is the genetic algorithm solver that is built-in to MATLAB. This solver will solve the stalagmite function for the inputs we have provided in the previous section of code. These outputs will have a fitness which is near optimum level and hence are suitable for the next generation.

The outputs of the stalagmite function will be stored in 2 arrays: \'inputs\' and \'fopt(i)\'. This follows the syntax, [inputs, fval] = ga(), where the \'ga\' solver will return the optimum value of the fitness function (fval) at x (inputs).

The optimum values for x and y are saved in the arrays \'xopt\' and \'yopt\' for every iteration of the for loop. These optimum values saved in the arrays are then used in the next iteration as they have been \'selected\' for their fitness. So they will go back in to the for loop to be input in to the stalagmite function where once again the outputs will be received and stored in the arrays for the next iteration. The process repeats till the end of the for loop.

The final 2 lines of code are converting the values stored in the arrays \'F\' and \'Fopt\' to their negative values in order to maximize the values obtained by the \'ga\' solver. This is needed since the solver would normally help in finding the function minima. So to find the maxima, we have created an array of the negatives of the optimum values stored in the arrays \'f\' and \'Fopt\'. The array \'f\' contains the solutions from the solving of the stalagmite shown in the last lines of code in the previous section. This is because the minmum value of the negative of a function, -f(x) is the maximum of f(x). The array \'Fopt\' contains the optimum values.

Plotting

%% Plotting 

figure(1)
subplot (2, 1, 1)
hold on
surfc(x, y, F)
shading interp
plot3(xopt, yopt, Fopt, \'marker\', \'o\', \'markersize\', 5, \'markerfacecolor\', \'red\')
xlabel (\'x\')
ylabel (\'y\')
zlabel (\'F\')
subplot (2, 1, 2)
plot(Fopt)
title (\'Unbounded Inputs\')
xlabel (\'No. of Iterations\')
ylabel (\'Function Maxima\')

In this section of code, the plotting of our results takes place. First a new figure window is opened. Then, the \'subplot\' command is used to create more than one graph in the same figure window. The code shows that we want 2 columns, 1 row and creates axes for the first graph. The \'hold on\' command is then used to retain the plots in the subplot. Then the \'surfc\' command is used to create a 3D surface plot with a contour plot underneath and does so in 3 axes.

The \'shading interp\' command varies the colour in each line segment and face by interpolating the colormap index across the line or face.

The \'plot3\' command is then used to plot the optimum x, y and function values in a 3D plot in the first graph on the subplot. A circle marker with size 5 and red colour is used. Axes labels are provided for all axes.

The subplot command is used again to reference the second graph in the subplot. This plot is for the plotting of the \'Fopt\' values i.e. the maximum values of the stalagmite function. A title is provided and the axes are labelled with the x axis for the number of iterations and the y axis for the maximum values.

Output

\"Case

The contour plot is rotated in 3D to get the view shown below:

\"Case

\"Case

As we can see from the contour plot, the maxima values are fluctuating all over the axes. This is because the values for the maxima have not been bounded i.e. constrained. So, the maxima values are exceeding the limits which would be suitable for the stalamite function. This is shown also in the second graph of the subplot showing the maxima values against the number of iterations.

In the second graph, for all 50 iterations, the maxima is not stable. So we know that from this first case that without restricting the values that the maxima can take, we will not get an accurate answer for the global maxima. Our search space was supposed to restrict the maxima to be between 0 and 0.6 but the \'ga\' algorithm does not know that since no bounds were set. Hence the title of these plots is \'Unbounded Inputs\'.

The time taken to execute the first case is shown in the screenshot below:

\"Case

As we can see, the time taken to run the first case was 4.55 seconds and is quite short.

Case 2 - Statistical Behavior with Upper and Lower Bounds

In the second case, we are going to attempt to solve the stalagmite function using the genetic algorithm to find the function maxima once again. This time, we will provide the genetic algorithm with constraints i.e. limits. These limits will be the in the form of upper and lower bounds. The purpose of this is to narrow the search for the maxima of the function and to obtain lesser fluctuation for a more accurate result of the maxima of the function.

clear all
close all
clc

% Defining the search space 

x = linspace (0, 0.6, 150);
y = linspace (0, 0.6, 150);
cases = 50;


% Creating a 2D mesh
[xx, yy] = meshgrid (x, y);


%% Evaluating the 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(input_vector);
    
    end
end

The above section of code is exactly the same as it was for Case 1. First we start with defining the search space using the \'linspace\' command. Then the number of cases is defined. After, a meshgrid is created using the search space with the \'meshgrid\' command. Then we evaluate the stalagmite function using a for loop where the \'i\' and \'j\' counters are used as a reference for coordinates to run through each and every value in the \'xx\' and \'yy\' arrays and input them in to the stalagmite function to get the output which is stored in the variable, \'f\'.

Bounds

%% With Upper and Lower Bounds

tic
for i = 1 : cases
    [inputs, fopt(i)] = ga(@stalagmite, 2, [], [], [], [], [0;0], [0.6;0.6 ]);
        xopt(i) = inputs(1);
        yopt(i) = inputs(2);
        
end

case2_time = toc

F = -f;
Fopt = -fopt;

In this section, first the timer is started using the \'tic\' command. Then the for loop is initiated which will run from 1 to 50 using the \'i\' counter. This for loop will get the optimum values of the stalagmite function and store them as the variables \'inputs\' and \'fopt\'. The \'ga\' solver is used once again for the stalagmite function. In the syntax for the \'ga\' function, we can input a set of limits for the upper and lower bounds. Since our search space is between 0 and 6 for x and y, the lower bounds are set to [0;0] and the upper bounds, to [0.6;0.6].

The syntax of the \'ga\' function is shown below:

x = ga(fun, nvars, A, b, Aeq, beq, lb, ub)

Since, we are not using any linear inequalities to define our constraints, those fields are kept blank with empty square brackets, [], as shown in the code above. Only the fields \'lb\' and \'ub\', referring to the lower and upper bounds respectively, are required for this case.

The \'ga\' function then selects the optimum x and y values and saves it to the arrays \'xopt\' and \'yopt\' for each iteration. So the arrays \'xopt\' and \'yopt\' are both of size 1x50. These optimum values afterwards are assigned to the variables inputs where the x value takes the 1st row and the y value takes the 2nd row. This can be seen with the indexing after the variable names.

The timer is stopped with the \'toc\' command and the time taken for running this script is saved to the variable \'case2_time\'. Once again to find the maxima of the stalagmite function, the values in the \'fopt\' array are converted to their negatives. The same is done for the function outputs stored in the array, \'f\' and equated to a variable, \'F\'. This is because the minmum value of the negative of a function, -f(x) is the maximum of f(x).

Plotting

%% Plotting
figure(2)
subplot (2, 1, 1)
hold on
surfc(x, y, F)
shading interp
plot3(xopt, yopt, Fopt, \'marker\', \'o\', \'markersize\', 5, \'markerfacecolor\', \'red\')
xlabel (\'x\')
ylabel (\'y\')
zlabel (\'F\')
title (\'Bounded Inputs\')
subplot (2, 1, 2)
plot(Fopt)
xlabel (\'No. of Iterations\')
ylabel (\'Function Maxima\')

In this section, just as was done with the first case, the code for the plotting is written. A subplot is created using the \'subplot\' command with 2 plots in one figure. A 3D surface plot is first created with a contour plot underneath. The \'shading interp\' command is used again.

The \'plot3\' command is then used to plot the optimum x, y and function values in a 3D plot in the first graph on the subplot. A circle marker with size 5 and red colour is used. Axes labels are provided for all axes.

The subplot command is used again to reference the second graph in the subplot. This plot is for the plotting of the \'Fopt\' values i.e. the maximum values of the stalagmite function. A title is provided and the axes are labelled with the x axis for the number of iterations and the y axis for the maximum values.

This time, the title of the plots is changed to \'Bounded Inputs\' referring to how for this study, limits were set in the form of the upper and lower bounds.

Outputs

The outputs graphs of the second case are shown below.

\"Bounded

When the above contour plot is rotated in 3D to get the view of the plot shown below:

\"Bounded

\"Case

From the contour plots, we can see that there is less variation in the value of the maxima for the stalagmite function. In the rotated 3D view, we can clearly see that the maxima varies is somewhere between the 2 peaks. This is more clearly interpreted from the maxima line graph. Compared to the first study, there is much less fluctuation and we can see that the maxima is more stable for more number of iterations.

So, this means that by setting bounds, we are getting closer and closer to the maxima of the stalagmite function. In a few iterations, the value of the maxima still seems to fluctutate between 0.74 and 0.97 approximately. However, as a whole the value of the maxima at each iteration is varying less and this ultimately means that we are getting closer to achieving termination due to convergence. This is where the population after each iteration is not significantly different from the previous generation.

The time taken for the second case is shown in the screenshot below:

\"Case

The time taken was 6.9 seconds and is longer than that of the first case.

Case 3 - Increasing the No. of Iterations

In this last case, the same code is written as for the previous 2 cases with a minor difference. This time, we will be increasing the number of iterations and using the constraints of the upper and lower bounds to obtain the maxima of the function as a more consistent value with lesser fluctuation. The aim of this study is to obtain an even more accurate and focused value for the global maxima than from the previous 2 cases

clear all
close all
clc

% Defining the search space 

x = linspace (0, 0.6, 150);
y = linspace (0, 0.6, 150);

cases = 50;

% Creating a 2D mesh
[xx, yy] = meshgrid (x, y);

The code for the third case starts exactly the same as in the previous 2 cases. The search space is defined and a 2D meshgrid is created with the search space.

%% Evaluating the 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(input_vector);
    
    end
end

In the evaluation stage, the code is exactly the same since increasing the number of iterations has nothing to do with changing how the maxima is calculated.

%% Increasing the Ga iterations

options = optimoptions(\'ga\');
options = optimoptions(options, \'PopulationSize\', 300);


tic
for i = 1 : cases
    [inputs, fopt(i)] = ga(@stalagmite, 2, [], [], [], [], [0;0], [0.6;0.6], [], [], options);
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end

case3_time = toc

F = -f;
Fopt = -fopt;

This section of code is where the changes are made with respect to the first 2 cases. Here, we are using another part of the syntax of the genetic algorithm function to increase the number of iterations. This is done using the \'optimoptions\' function which creates optimization options.

In the \'ga\' syntax, after the upper and lower bounds, there is a field called \'options\'. The synax is shown below: x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon,options)

The \'options\' field allows us to set extra parameters and we can use this to maximise the function. The \'optimoptions\' syntax is shown below: options = optimoptions(SolverName)

This same syntax is followed in the first line of code in the section above. The solver name is \'ga\' because that is what we are using to solve the stalagmite function.

The syntax for the \'optimoptions\' function when the parameters to be added are named is shown below: options = optimoptions(prob,Name,Value)

This same synax is followed in the second line of code in the section above. The named parameter is \'PopulationSize\' and the specified value is \'300\'.

The remaining lines of code are almost the same as before. The time taken to run the code is measured with the \'tic\' and \'toc\' commands and is saved to the variable \'case3_time\'.

The for loop is the same except for the syntax of the \'ga\' function. This will change using the syntax mentioned earlier. After the \'lb\' and \'ub\' fields, the next 2 fields are empty and the field after is filled as \'options\'.

Adding this \'options\' to the end will integrate the new parameter of \'PopulationSize\' and its specified value, 300 in to the \'ga\' argument.

The negatives of the \'fopt\' array are created and saved to the array \'Fopt\'. The same is done for the outputs from stalagmite function, \'f\' and the values are assigned to the variable, \'F\'.

Plotting

%% Plotting
figure(3)
subplot(2,1,1)
hold on
surfc(x, y, F)
shading interp
plot3(xopt, yopt, Fopt, \'marker\', \'o\', \'markersize\', 5, \'markerfacecolor\', \'red\')
xlabel(\'x\')
ylabel(\'y\')
zlabel(\'F\')
title(\'GA Statistical Behavior with increased interations\')
subplot(2,1,2)
plot(Fopt)
xlabel(\'No. of Iterations\')
ylabel(\'Function Maxima\')

The plotting commands are unchanged. It is exactly the same except the title is changed to show that this case is showing the statistical behavior with increased iterations.

Outputs

\"Case

Once again, the above contour plot is rotated in 3D to get the view below:

\"Case

\"Case

As we can see from the contour plot, the maxima of the function is centered at only one peak. The image below shows the coordinate of that point:

\"3D

Looking at the Z coordinate, the maxima of the function is said to be 0.9693. The contour plots show less variation in maxima points and is more focused on a single value. The value of the maxima is much more accurate since the maxima values are closer and closer to the true value. The maxima values are more precise as well since the variation between results is very less. This shows that the termination stage of the genetic algorithm is achieved. Compared to the first 2 studies, there is almost very little to no fluctuation. However, contour plots cannot show us detail.

So the second graph of the Maximum value vs. number of iterations shows this in more detail. As we can see, the maxima still seems to vary however this variation is very negligible because it is happening on a scale of 0.00001. If the axes scale of the y axis was changed, this would appear as a horizontal line at 0.9693 which matches with the Z coordinate shown by the contour plot.

Even the 2 sharp dips between 17 and 20 iterations and 33 and 35 iterations is not significant as it is also if a negligible scale. Since the value of the maxima is not changing significantly between the generations/iterations, we can see that this is characteristic of the termination phase in the genetic algorithm process.

So, the maxima of the function is very near and will only get nearer as the number of iterations increases or if the population size increases.

The time taken to execute the third case is shown in the screenshot below:

\"Case

The time taken for case 3 was 21.78 seconds which is considerably larger than it was for the first 2 cases. This is attributed to the larger number of iterations and processing of calculations which is a tradeoff for obtaining a closer and more accurate value for the maxima of the stalagmite function.

Errors

  • Error 1

\"Error

In the image above, you can see that the first error I faced was in the code for the creation of the stalagmite function. I made a mistake in the code where I used square brackets to enclose the \'input_vector\' variable. I should have used parentheses instead as shown in the warning message in the command window. The correction was made easily.

  • Error 2

\"Error

The second error I faced was in the main body of the \'ga\' script. I made the mistake of naming my script for the code as \'ga.m\'. This led to the warning message shown in the command window because \'ga\' is also the name of the function for the calling of the genetic algorithm solver. So, we cannot name a file with the same name as an in-built function/solver in MATLAB. This error was easily rectified by renaming my script file as \'ga_stalagmite.m\' instead.

Conclusion

The genetic algorithm was used as a model to solve the stalagmite function in order to determine its global maxima. The output graphs and times taken for each case have been shown above. It is evident that by increasing the number of iterations, increasing the population, and by setting constraints in the form of upper and lower bounds, the result for the global maxima becomes more accurate despite taking longer to compute. From the third case, it appears that the global maxima is approaching the value of 0.9693 and in the previous cases, this same value was nearly achieved accurately.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.