Challenge

Week 4.1 - Genetic Algorithm

clear all
close all
clc
% Defining search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);

n = 50;
% Creating a 2-D mesh
[a b] = meshgrid(x,y)

% Evaluating the Stalagmite function
for i = 1:length(a)
    for j = 1:length(b)
        input_vector(1) = a(i,j);
        input_vector(2) = b(i,j);
        f(i,j) = stalagmite(input_vector);
    end
end

surfc(a,b,f)
xlabel(\'x value\')
ylabel(\'y value\')
shading interp
hold on

[inputs,fval]= ga(@stalagmite,2)

tic
% Study1 - Behaviour without boundary conditions
for i = 1:n
    [inputs,fopt(i)] = ga(@stalagmite,2);
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end
study_time = toc


figure(1)
subplot(2,1,1)
hold on
surfc(x,y,f)
xlabel(\'x value\')
ylabel(\'y value\')
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 minimum\')


% Study 2 - Under upper and lower boundaries

tic
for m = 1:n
    [inputs,fopt(m)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
    xopt(m) = inputs(1);
    yopt(m) = inputs(2);
end
study2_time = toc;

figure(2)
subplot(2,1,1)
hold on
surf(x,y,f)
xlabel(\'x value\')
ylabel(\'y value\')
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 minimum\')

% Study 3- Increaing the iterations
options = gaoptimset(\'ga\')
options = gaoptimset(options,\'populationsize\',400)
tic
for o = 1:n
[inputs,fopt(o)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],options);
xopt(o)
yopt(o)
end
study3_time = toc
figure(3)
subplot(2,1,1)
hold on
surf(x,y,f)
xlabel(\'x value\')
ylabel(\'y value\')
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 minimum\')

figure(4)
surfc(a,b,f)
xlabel(\'x value\')
ylabel(\'y value\')
shading interp

[inputs,fopt(o)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],options);

study_time,study2_time,study3_time

The code for the define stalagmite fuction is written below.

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 = 1/(1+(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.