Challenge

Week 4.1 - Genetic Algorithm

Main code for MATLAB to optimise the stalagmite function and find the global maxima of the function.

clear all
close all
clc

%inputs and generation of 2d array
x=linspace(0,1,150);
y=linspace(0,1,150);
num_space = 50;

[xx,yy]=meshgrid(x,y);
for i=1:length(x)
    for j=1:length(y)
        input_vector(1)=xx(i,j);
        input_vector(2)=yy(i,j);
        f(i,j)=stalagmite_fn(input_vector);
    end
end

%study 1
tic
for i=1:num_space
    [inputs,fopt(i)]=ga(@stalagmite_fn,2);
    xopt(i)=inputs(1);
    yopt(i)=inputs(2);
end
study_time1=toc

%plotting with subplots for better understanding
figure(1);
subplot(2,1,1);
surf(x,y,-f);
shading interp;
hold on;
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r');
subplot(2,1,2);
plot(-fopt);
xlabel('iteration');
ylabel('f_maximum');
title('Unbounded_inputs');

%study2 : Bounded  inputs

tic
for i=1:num_space
    [inputs,fopt(i)]=ga(@stalagmite_fn,2,[],[],[],[],[0;0],[1;1]);
    xopt(i)=inputs(1);
    yopt(i)=inputs(2);
end
study_time2=toc

%plotting with subplots for better understanding
figure(2);
subplot(2,1,1);
surf(x,y,-f);
shading interp;
hold on;
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r');
subplot(2,1,2);
plot(-fopt);
xlabel('iteration');
ylabel('f_maximum');
title('Unbounded_inputs');

%study 3:Increased number of iterations
tic
options=optimoptions('ga');
options=optimoptions(options,'populationsize',300);
for i=1:num_space
    [inputs,fopt(i)]=ga(@stalagmite_fn,2,[],[],[],[],[0;0],[1;1],[],[],options);
    xopt(i)=inputs(1);
    yopt(i)=inputs(2);
end
study_time3=toc

%plotting with subplots for better understanding
figure(3);
subplot(2,1,1);
surf(x,y,-f);
shading interp;
hold on;
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r');
subplot(2,1,2);
plot(-fopt);
xlabel('iteration');
ylabel('f_maximum');
title('Unbounded_inputs');


Code for stalagmite function

function [A]=stalagmite_fn(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);
A=-(f1*f2*f3*f4);
    

PLots for the studies are shown in the report.

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.