Challenge

Week 4.1 - Genetic Algorithm

Code for stalagmite function:

function [f] = stalagmite(input_vector)
f1x = [sin(5.1*pi*input_vector(1) + 0.5)].^6;
f1y = [sin(5.1*pi*input_vector(2) + 0.5)].^6;
f2x = exp((-4*log(2))*(input_vector(1) - 0.0667).^2/0.64);
f2y = exp((-4*log(2))*(input_vector(2) - 0.0667).^2/0.64);

f = -(f1x*f1y*f2x*f2y);
end

main code:

clear all
close all
clc

% Defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
iterations = 50;

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

% Evaluating the stalagmite function
for i = 1:length(xx)
for i = 1:length(yy)
input_vector(1) = xx(i,i);
input_vector(2) = yy(i,i);
F(i,i) = stalagmite(input_vector);
end
end


% Study 1 - Unbounded inputs
tic
for i = 1:iterations;
[inputs,Fo(i)]=ga(@stalagmite,2);
xo(i)=inputs(1);
yo(i)=inputs(2);
end

study_time1 = toc

figure(1)
subplot(2,1,1)
hold on
colorbar
surfc(xx,yy,-F);
shading interp;
plot3(xo,yo,-Fo,'marker','o', 'markersize', 5);
xlabel('y data');
ylabel('x data');
tile('unbounded inputs');
subplot(2,1,2);
plot(-Fo);
xlabel('Iterations');
ylabel('Function maximum');

% Study2 - with upper and lower bounds
tic
for j = 1:iterations
[inputs,Fo(j)]=ga(@stalagmite,2,[],[],[],[],[0:0],[1:1]);
xo(i)=inputs(1);
yo(i)=inputs(2);
end

study_time2 = toc;

figure(2)
subplot(2,1,1)
hold on
colorbar
surfc(xx,yy,-F);
shading interp;
ylabel('y data');
xlabel('x data');
plot3(xo,yo,-Fo,'marker','o', 'markersize', 5);
title('Bounded inputs');
subplot(2,1,2);
plot(-Fo);
xlabel('Iterations');
ylabel('Function maximum');


%Study3 - Increasing iterations by increasing population size
options = optimoptions('ga','populationsize',250);
tic
for k = 1:iterations
[inputs,Fo(k)]=ga(@stalagmite,2,[],[],[],[],[0:0],[0,6:0,6],[],[],options);
xo(k)=inputs(1);
yo(k)=inputs(2);
end

study_time3 = toc

figure(3)
subplot(2,1,1);
colorbar
hold on
surfc(xx,yy,-F);
shading interp;
ylabel('y data');
xlabel('x data');
plot3(xo,yo,-Fo,'marker','o', 'markersize', 5);
title('bounded inputs with increased population size')
subplot(2,1,2);
plot(-Fo);
xlabel('Iterations');
ylabel('Function maximum');

Output:

Global optimization toolbox missing in MATLAB trial use so could not obtain the results.

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.