Thursday, June 16, 2011

Basics of the Genetic Algorithm in Matlab

The Genetic algorithm is based on the idea of Natural Selection as propounded by Charles Darwin. Study of the Genetic Algorithm serves to important purposes:-
1) It leads to a better understanding of Nature itself.
2) Provides a means for optimizing artificial systems based on the Genetic Algorithm.


The Genetic Algorithm is superior to the other optimization techniques because :-
1) It does not require the existence of the derivative as in the calculus method.
2) It is faster and more stable than enumeration methods and/or random methods like Dynamic Programming, Branch & Bound, Backtracking etc. It's memory requirements are also much less.


The Genetic algorithm requires a fitness function which decides the selection, the reproduction function, mutation & Cross Over.

Working Procedure:-
1)Create a function file giving the fitness function.
2)Create the inequality matrix, the equality matrix, the lower bound matrix, the upper bound matrix.Remember all of these are optional.
3) Multiply by -1 to adjust the inequalities as well as to transform minimization problems to maximization and vice versa.
Let us solve two optimization problems using the Genetic Algorithm:-
1) Minimize z=-x1 + 2x2
subject to the constraints
-x1 + 3x2<10
x1 + x2<6
x1-x2<2
x1>=0 and x2>=0
First of all create the inequalities matrix a
>> a=[-1 3;1 1;1 -1];
>> a

a =

    -1     3
     1     1
     1    -1

>> 

Create matrix b
>> b=[10; 6; 2];
>>
>> b

b =

    10
     6
     2
>> Create the lower bound matrix lb
>> lb=[0;0];
>> lb

lb =

     0
     0

>> 

Now, create the function file abc.m containing the fitness function:-
abc.m
function y=  abc( x)
y=-x(1) + 2*x(2);

end












Call the optimizer using ga as the solver. use empty bracket [] for the optional parts which are not to be given.
>> [x,fval,exitflag] = ga(@abc,2,a,b,[],[],lb)
Optimization terminated: average change in the fitness value less than options.TolFun.

x =

    2.0010         0


fval =

   -2.0010


exitflag =

     1

>>


The answer is x1=2.0010 , x2=0
and the minimized value is -2.0010


Problem No 2
Minimize z= 20x1 + 40 x2
subject to the constraints
36x1 + 6x2 >=108
3x1 + 12x2 >=36
20x1 + 12x2>=100
x1>0 and x2>0
since the constraints are of the >= type , we shall multiply each equation by -1

-36x1 - 6x2 <=-108
-3x1 - 12x2 <=-36
-20x1 - 12x2<=-100


>> a=[-36 -6;-3 -12;-20 -10];
>> a

a =

   -36    -6
    -3   -12
   -20   -10

>> b=[-108;-36;-100];
>> b

b =

  -108
   -36
  -100

>> lb=[0;0];
>> lb

lb =

     0
     0

>> [x,fval,exitflag] = ga(@abc,2,a,b,[],[],lb)
Optimization terminated: average change in the fitness value less than options.TolFun.

x =

    4.0000    1.9999


fval =

  159.9966


exitflag =

     1

>> 

abc.m

function y=  abc( x)
y=20*x(1) + 40*x(2);

end

















No comments:

Post a Comment