Tuesday, February 26, 2013

Solving problems using GA in Matlab

This was an assignment in the 1st semester of my MSc. in AI, at University of Moratuwa for the subject 'Evolutionary Computing'.

Given below are some example problems and how I solved them using the GA Optimization toolkit in Matlab 2012Rb.

Problem 1 : solving simultaneous equations

2x+y = 8
x+y = 6

Select 'Double Vector' for the population. Set 'Number of variables' as 2. Set 'Integer variable indices' as [1,2]. Use the correct fitness function and run the GA using the rest of the default values.

The fitness function I used is given below..

function fitness = optimization(params)
fitness1 = 8 - 2* params(1) - params(2);
fitness2 = 6 - params(1) - params(2);
if(fitness1 < 0 )
    fitness1 = -fitness1;
if(fitness2 < 0 )
    fitness2 = -fitness2;
fitness = fitness1 + fitness2;

You can change the default values and observe how the output value changes..

Problem 2 : solving a profit optimization problem

Suppose a fruit seller has 5 different kinds of fruits to sell. They are, mango(m), banana(b), strawberry(s), peach(p), orange(o). Suppose the profit from selling each fruit is as follows, mango - 30,banana - 15, strawberry - 50, peach - 20, orange - 10. If the fruit seller wants to make a profit of 10,000 how many fruits of each type should he sell?

Select Double Vector for the population. Since there are 5 types of fruits. You need a chromosome with 5 genes. Set 'Number of variables' as 5. You should specify that the minimum value for each variable is 0 by giving the lower bound as the vector [0,0,0,0,0]. You should also specify that the variables can only take integer values by giving the 'Integer variable indices' as [1,2,3,4,5]. Next you must specify the fitness function.

The fitness function I used is given below:

function fitness = fruits(params)
m = params(1);
b = params(2);
s = params(3);
p = params(4);
o = params(5);
fitness = 10000 - m*30-b*15-s*50-p*20-o*10;
if (fitness < 0)
    fitness = -1*fitness;

After setting these values you can simply run the GA with the rest of the default values. The output I got was,
m = 26, b = 230, s= 19, p = 95, o = 292 which gives a profit of exactly 10,000.

The corresponding graphs are give below..

You can change the default values and observe how the output value changes..


  1. it is great...!!! and really useful for me..Harini , Thanks lot

  2. exelent, Might acer examples using nonlinear constrains function? please