Challenge

Week 5 - Genetic Algorithm

function code for genetic algorithm

function [f] = stalagmite(input_vector)
% input_vector(1) = x;
% input_vector(2) = y;
fx = (sin(5.1*pi*input_vector(1)+0.5))^6;
fy = (sin(5.1*pi*input_vector(2)+0.5))^6;
fxx = exp(-4*log(2)*((input_vector(1)-0.0667)^2)/0.64);
fyy = exp(-4*log(2)*((input_vector(2)-0.0667)^2)/0.64);
f = -(fx*fy*fxx*fyy);
end
%optimise the stalagmite function

clear all
close all
clc


% 1) input for search space

x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_case = 50;

% 2) use of meshgrid command

[xx,yy] = meshgrid(x,y);


% 3) evaluating objective fuunction by using nested for loop

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

surfc(x,y,-f)
shading interp

% 1st case study

tic
for i=1:num_case
    [inputs,fopt(i)] = ga(@stalagmite,2);

    xopt(i) = inputs(1);
    yopt(i) = inputs(2);

end

fopt = -fopt
time_study1 = toc


figure(1)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,fopt,'Marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('bounded inputs')
%figure(2)
subplot(2,1,2)
plot(fopt)
xlabel('Iteration')
ylabel('Function maximum')


% 2nd case study


tic
for i=1:num_case
    [inputs2,fopt2(i)] = ga(@stalagmite,2,[],[],[],[],[0,0],[0.6,0.6]);

    xopt2(i) = inputs2(1);
    yopt2(i) = inputs2(2);

end

fopt2 = -fopt2
time_study2 = toc


figure(2)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt2,yopt2,fopt2,'Marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('bounded inputs')
%figure(2)
subplot(2,1,2)
plot(fopt2)
xlabel('Iteration')
ylabel('Function maximum')



% 3rd case study


options = optimoptions('ga')
options = optimoptions(options,'PopulationSize',500);


tic
for i=1:num_case
    [input3,fopt3(i)]=ga(@stalagmite,2,[],[],[],[],[0,0],[0.6,0.6],[],[],options);
    xopt3(i) = input3(1);
    yopt3(i) = input3(2);

end

fopt3 = -fopt3
time_study3 = toc



figure(3)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt3,yopt3,fopt3,'Marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('bounded inputs')
%figure(2)
subplot(2,1,2)
plot(fopt3)
xlabel('Iteration')
ylabel('Function maximum')

​
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.