MATLAB - Genetic Algorithm using MATLAB
Genetic Algorithm using MATLAB
Objective
To write a program on MATLAB to determine the global maxima and minima of a stalagmite function using genetic algorithm.
Procedure
In computer science and operations research, a genetic algorithm (GA) is a metaheuristic inspired by the process of natural selection that belongs to the larger class of evolutionary algorithms (EA). Genetic algorithms are commonly used to generate high-quality solutions to optimization and search problems by relying on bio-inspired operators such as mutation, crossover and selection.MATLAB comes with the in-built genetic algorithm function 'ga' which will be made use of in this program
Main Program
clear all
close all
clc
%defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_cases = 50;
f = get_stalagmite(x,y);
%creating a 2Dimensional mesh
[xx yy] = meshgrid(x , y);
%Ealuating 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(input_vector);
endfor
endfor
%case study 1
tic
for i = 1:num_cases
[inputs, fopt(i)] = ga(@stalagmite,2);
xopt(i) = inputs(1);
yopt(i) = inputs(2);
endfor
study1_time = toc;
figure(1)
subplot(2,1,1)
hold on
surfc(xx,yy,f)
shading interp
xlabel('x values')
ylabel('y values')
zlabel('function values')
hold on
plot3(xopt,yopt,-fopt,'marker', 'o','markersize',5,'markerfacecolor','g')
subplot(2,1,2)
plot(-fopt)
xlabel('íterations')
ylabel('function maximum')
%case study 2
tic
for i = 1:num_cases
[inputs , fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0:0],[0.5:0.5]);
xopt(i) =inputs(1);
yopt(i) = inputs(2);
endfor
study2_time = toc
figure(2)
subplot(2,1,1)
hold on
surfc(xx,yy,f)
shading interp
xlabel('x values ')
ylabel('y values')
zlabel( 'function values')
hold on
plot3(xopt,yopt,-fopt,'marker','o', 'markersize', 5, 'markerfacecolor', 'g')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations')
ylabel( 'function maximum')
Function
clear all
clc
function[f] = stalagmite(inputvector)
x = inputvector(1);
y = inputvector(2);
f1x = (sin(5.1*pi()*x+0.5))^6
f1y = (sin(5.1*pi()*y+0.5))^6
f2x = exp(-4*log(2)*((x-0.667)^2)/0.64);
f2y = exp(-4*log(2)*((y-0.667)^2)/0.64);
f = -f1x*f1y*f2x*f2y;
endfunction