Challenge

Week 4.1 - Genetic Algorithm

clear all
close all
clc
%define the search space
%assign the values for x&y by taking 150 values in btwn 0 & 0.6
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
%Num_spaces is no of iterartions
num_cases=50;
%To create two dimensional array
[xx,yy]=meshgrid(x,y);
% To evaluate 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_func(input_vector);
end
end

surfc(xx,yy,f);
shading interp
%fval=function value
[x,fval]=ga(@stalagmite_func,2);

%study-1,unbound
tic
for i=1:num_cases
[inputs,fopt(i)]=ga(@stalagmite_func,2)
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
%the results are stored into the variables xopt&yopt,
%to get 3d surface,plot(x,y,-f)

study1_time=toc
figure(1)
subplot(2,1,1);
hold on
surfc(x,y,f)
shading interp
plot3(xopt,yopt,fopt,'marker','o');
subplot(2,1,2);
plot(fopt);
xlabel('Iteration')
ylabel('Function maximum')

%study 2-bounded
%we have lower and upper bouns in this cases,ranges from 0 to 0.6

tic
for i=1:num_spaces
[inputs,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6]);
xopt(i)=inputs(1);
yopt(i)=inputs(2);
end
study2_time=toc
figure(2)
subplot(2,1,1);
surfc(x,y,f)
shading interp
hold on
plot3(xopt,yopt,fopt,'marker','o');
subplot(2,1,2);
plot(fopt);
xlabel('Iteration')
ylabel('Function maximum')

%study 3-Increased initial population
tic
options=optimoptions('ga');
options=optimoptions(options,'populationsize',200);
for i=1:num_cases
[results,fopt(i)]=ga(@stalagmite_func,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);
surfc(x,y,f)
shading interp
hold on
%to get optimum maximum plotxopt,yopt,and fopt
plot3(xopt,yopt,fopt,'marker','o')
subplot(2,1,2)
plot(fopt)
xlabel('Iteration')
ylabel('Function maximum')


% code for stalagmite function
function A=stalagmite_func(input_vector)
x=input_vector(1);
y=input_vector(2);
f1=(sin(5.1*pi*x+0.5)).^6;
f2=exp((-4*log(2))*((x-0.0667).^2)/0.64);
f3=(sin(5.1*pi*y+0.5)).^6;
f4=exp((-4*log(2))*((y-0.0667).^2)/0.64);
A=(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.