Challenge

Week 4.1 - Genetic Algorithm

clear all
close all
clc
%Defining our search space
x=linspace(0,0.6,150);  %Creating one dimensional array of X & Y  
y=linspace(0,0.6,150);

[xx, yy]=meshgrid(x,y); % Based on one dimensional array, creating two dimensional array
%Evaluating the stalagmite function
for i = 1:length(xx)
    for j=1:length(yy)
        input_vector(1)=xx(i,j); %creating an array of row vector
        input_vector(2)=yy(i,j);
       f(i,j)=stalagmite(input_vector); %Generating plot for stalagmite mathematical model
    end
end

tic
%study 1_statistical behaviour
num_cases=50; %Running GA for 50 times
for i=1:num_cases
    [inputs,fopt(i)]=ga(@stalagmite,2); %Performing genetic algorithm to find maximum value
    xopt(i)=inputs(1); %Storing X & Y opt values
    yopt(i)=inputs(2);
end
study1_time=toc %Measuring how long it takes

figure(1)
subplot(2,1,1) %To have multiple plots inside the same figure window
hold on
surfc(xx,yy,-f) %Using surface plot to visualize
xlabel('xaxis')
ylabel('yaxis')
shading interp %Enabling shading instead of lines
plot3(xopt,yopt,-fopt,'marker','o','markerSize',5,'markerfacecolor','r') %Plotting x,y,f optimum values over 50 times
title('unbounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations') %Labelling
ylabel('function maximum')

tic
%study 2-statistical behaviour- with upper and lower bounds
for i=1:num_cases
    [inputs,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6]); %assigning lower and upper bounds
    xopt(i)=inputs(1);
    yopt(i)=inputs(2);
end
study2_time=toc
figure(2)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
xlabel('xaxis')
ylabel('yaxis')
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')


%study 3 increasing GA iteration
options=optimoptions('ga'); 
options=optimoptions(options,'PopulationSize',150) %Increasing the population size

tic
for i=1:num_cases
    [inputs, fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
    xopt(i)=inputs(1);
    yopt(i)=inputs(2);
end
study3_time=toc
figure(3)
subplot(2,1,1)
hold on
surfc(x,y,-f)
xlabel('xaxis')
ylabel('yaxis')
shading interp
plot3(xopt,yopt,-fopt,'Marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('bounded inputs with population size')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations')
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.

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.