Week 5 - Genetic Algorithm
% Genetic Algorithm Optimization of the Stalagmite Function
% Define the Stalagmite Function
function f = stalagmite(x)
f = (sin(5.1*pi*x(1) + 0.5*pi))^6 * (sin(5.1*pi*x(2) + 0.5*pi))^6;
end
% Main Script
clc;
clear;
close all;
% Set the random seed for reproducibility
rng(1);
% Define the fitness function as a handle to the stalagmite function
fitnessFunction = @(x) -stalagmite(x); % Minimize negative to maximize original
% Number of variables
nvars = 2;
% Set options for the Genetic Algorithm
options = optimoptions('ga', 'PlotFcn', @gaplotbestf, 'MaxGenerations', 100, 'Display', 'iter');
% Run the Genetic Algorithm
[x, fval] = ga(fitnessFunction, nvars, [], [], [], [], [0 0], [1 1], [], options);
% Display the results
disp(['Global Maximum found at: x1 = ', num2str(x(1)), ', x2 = ', num2str(x(2))]);
disp(['Function value at Global Maximum: ', num2str(-fval)]);
% Plot the Stalagmite Function
figure;
fsurf(@stalagmite, [0 1 0 1]);
title('Stalagmite Function');
xlabel('x1');
ylabel('x2');
zlabel('f(x)');