Challenge

Week 4.1 - Genetic Algorithm

Main program

clear all
close all
clc

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


% creating a 2dimensional 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

surf(xx,yy,-f);
shading interp;
hold on

% genetic algorithm
[inputs, fval] = ga(@stalagmite,2,[],[],[],[],[0,0],[0.6,0.6])

% plotting global maxima
figure(1)
x_max = inputs(:,1);
y_max = inputs(:,2);
f_max = -fval;
plot3(x_max,y_max,f_max, 'marker','o','MarkerSize',5,'MarkerFaceColor','r')
xlabel('x_value')
ylabel('y_value')
title('GLOBAL MAXIMA')
legend('stalagmite','global maxima')


% study1 - stastical behavior
tic
for i = 1:num_cases
    [inputs, fopt(i)] = ga(@stalagmite,2);
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end

study1_time = toc

figure(2)
subplot(2,1,1)
hold on
surf(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt, 'marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('unbounded inputs')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('function maximum')


% study2 - stastical behavior with upper & lower bounds
tic
for i = 1:num_cases
    [inputs, fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end

study2_time = toc

figure(3)
subplot(2,1,1)
hold on
surf(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt, 'marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('bounded inputs')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('function maximum')

% study3 - increasing GA iterations
options = optimoptions('ga');
options = optimoptions(options, 'PopulationSize', 170);

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

study3_time = toc

figure(4)
subplot(2,1,1)
hold on
surf(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt, 'marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('bounded inputs with modified population size')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('function maximum')


stalagmite program

function [f] = stalagmite(input_vector)
x = input_vector(1);
y = input_vector(2);

f1 = (sin(5.1*pi*x+0.5))^6;
f2 = (sin(5.1*pi*y+0.5))^6;
f3 = exp(-4*log(2)*(x-0.0667)^2/0.64);
f4 = exp(-4*log(2)*(y-0.0667)^2/0.64);

f = -(f1*f2*f3*f4);
end




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.