Challenge

Week 5 - Genetic Algorithm

clc; clear; close all;
% Stalagmite Function
stalagmite = @(x) (sin(5.1 * pi * x(:,1)).^6) .* (sin(5.1 * pi * x(:,2)).^6);
% Fitness Function for GA
fitnessFunc = @(x) -stalagmite(x); % GA minimizes by default, so negate function
% GA Options (Fixed for Repeatability)
options = optimoptions('ga', 'PopulationSize', 50, 'MaxGenerations', 100, ...
'EliteCount', 2, 'CrossoverFraction', 0.8, 'MutationFcn', {@mutationgaussian, 0.01}, ...
'PlotFcn', {@gaplotbestf}, 'Display', 'iter');
% Study 1: Random Initialization
[x1, f1] = ga(fitnessFunc, 2, [], [], [], [], [0 0], [1 1], [], options);
% Study 2: Uniform Initialization
rng(1); % Setting fixed random seed
options.InitialPopulationMatrix = rand(50,2); % Ensuring uniform distribution
[x2, f2] = ga(fitnessFunc, 2, [], [], [], [], [0 0], [1 1], [], options);
% Study 3: Fine-tuned GA Parameters (More Generations, Different Mutation Rate)
options.MaxGenerations = 200;
options.MutationFcn = {@mutationgaussian, 0.02}; % Increased mutation rate
[x3, f3] = ga(fitnessFunc, 2, [], [], [], [], [0 0], [1 1], [], options);
% Display Results
fprintf('Study 1: Optimal x: %.4f, %.4f | Max Value: %.4f\n', x1(1), x1(2), -f1);
fprintf('Study 2: Optimal x: %.4f, %.4f | Max Value: %.4f\n', x2(1), x2(2), -f2);
fprintf('Study 3: Optimal x: %.4f, %.4f | Max Value: %.4f\n', x3(1), x3(2), -f3);
% 3D Surface Plot of Stalagmite Function
[X, Y] = meshgrid(0:0.01:1, 0:0.01:1);
Z = stalagmite([X(:), Y(:)]);
Z = reshape(Z, size(X));
figure;
surf(X, Y, Z);
hold on;
plot3(x1(1), x1(2), -f1, 'ro', 'MarkerSize', 10, 'MarkerFaceColor', 'r');
plot3(x2(1), x2(2), -f2, 'go', 'MarkerSize', 10, 'MarkerFaceColor', 'g');
plot3(x3(1), x3(2), -f3, 'bo', 'MarkerSize', 10, 'MarkerFaceColor', 'b');
xlabel('x1'); ylabel('x2'); zlabel('Stalagmite Function');
title('Optimization of Stalagmite Function with GA');
legend('Study 1', 'Study 2', 'Study 3');
colorbar; grid on;
% F_max vs. Iterations
generations = 1:options.MaxGenerations;
F_max_values = [-f1, -f2, -f3];
figure;
plot(generations, F_max_values(1) * ones(size(generations)), 'r', 'LineWidth', 1.5);
hold on;
plot(generations, F_max_values(2) * ones(size(generations)), 'g', 'LineWidth', 1.5);
plot(generations, F_max_values(3) * ones(size(generations)), 'b', 'LineWidth', 1.5);
xlabel('Iterations'); ylabel('F_{max}');
title('F_{max} vs Iterations');
legend('Study 1', 'Study 2', 'Study 3');
grid on;

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.