Genetic Algorithm: General Concept, Matlab Code, and Example

In this video, I’m going to show you a general concept, matlab code, and one benchmark example of genetic algorithm for solving optimization problems.

This video tutorial was designed for beginners, and I tried to make it as simple as possible. Once you understand this foundation, you can be able to customize and design your own version of genetic algorithm to solve optimization problems in your fields.

Did you know that Genetic algorithm (GA) is one of the most popular stochastic optimization algorithm often used to solve complex large scale optimization problems in various fields.

Here is the general concept of genetic algorithm (Gen & Cheng 1997, pp.1-2):

Genetic Algorithm was first introduced by Holland in 1975, and it is a powerful stochastic search algorithm based on the mechanisms of natural genetics and selection. A general description of genetic algorithm is as follows:

+ Genetic algorithm starts with an initial set of random solutions called population.

+ Each individual in the population is called a chromosome representing a solution to the problem at hand.

+ The chromosomes evolve through successive iterations, called generations.

+ During each generation, the chromosomes are evaluated using some measures of fitness.

+ To create the next generation, new chromosome, called offspring, are formed by either (a) merging two chromosomes from current generation using a crossover operator or (b) modifying a chromosome using a mutation operator.

+ A new generation is formed by (a) selecting, according to the fitness values, some of the parents and offspring and (b) rejecting others so as to keep the population size constant.

+ Fitter chromosomes have higher probabilities of being selected.

+ After several generations, the algorithms converge to the best chromosome, which hopefully represents the optimum or suboptimal solution to the problem.

Let’s see how this genetic algorithm works.

For more videos like this, check my YouTube channel here.

Matlab code

mutation.m

function Y=mutation(P,n)
% P = population
% n = chromosomes to be mutated
[x1 y1]=size(P);
Z=zeros(n,y1);
for i = 1:n
    r1=randi(x1);
    A1=P(r1,:); % random parent
    r2=randi(y1);
    if A1(1,r2)== 1
        A1(1,r2) = 0; % flick the bit
    else
        A1(1,r2) = 1;
    end
    Z(i,:)=A1;
end
Y=Z;

crossover.m

function Y=crossover(P,n)
% P = population
% n = number of pairs of chromosomes to be crossovered
[x1 y1]=size(P);
Z=zeros(2*n,y1); 
for i = 1:n
    r1=randi(x1,1,2);
    while r1(1)==r1(2)
        r1=randi(x1,1,2);
    end
    A1=P(r1(1),:); % parent 1
    A2=P(r1(2),:); % parent 2
    r2=1+randi(y1-1); % random cutting point
    B1=A1(1,r2:y1);
    A1(1,r2:y1)=A2(1,r2:40);
    A2(1,r2:40)=B1;
    Z(2*i-1,:)=A1; % offspring 1
    Z(2*i,:)=A2; % offspring 2
end
Y=Z;

population.m

function Y = population(n)
% n = population size

% It is noted that the number of bits to represent the variables 
% in binary numbers depends on the required accuracy (the number 
% of digits after comma)

% In this example, I want the solution precision with 5 places after the
% decimal point, and with the upper and lower bounds of the variables are 3
% and -3, so, for each variable, we need 20 bits.
% General formula: 2^(m-1) < (upper bound - lower bound)*10^p < 2^m -1
% In this case: p = 5 and m = 20.

% We have 2 variables (x and y), so we need 40 bits in
% total for binary encoding
Y=round(rand(n,40)); 

evaluation.m

function Y=evaluation(P)
[x1 y1]=size(P);
H=zeros(1,x1);
for i = 1:x1
    A=bi2de(P(i,1:y1/2));
    x=-3+A*(3-(-3))/(2^(y1/2)-1);
.
.
.
Sorry! This is only a half of the Matlab code.

Notice: It would take you from 1 to 3 hours to re-type the Matlab code yourself; or with just €1.99 (the cost of a cup of coffee), you can download/copy the whole Matlab code within 2 minutes. It’s your choice to make.

Original price is €3.99 but today it’s only €1.99 (save €2 today – available for a limited time only)

Download the whole Matlab code here (Membership Code ID: 032)

No need to build the Matlab code from scratch because it’s very time-consuming. My idol, Jim Rohn, once said: “Time is more value than money. You can get more money, but you cannot get more time”. If you think this code can be used in your research/teaching work, you should download it and then customize/modify/apply it to your work, without any obligation of citing the original source if you don’t want. However, redistribution (i.e., downloading the code/script here and then making it available on another site on the Internet) is strictly prohibited.

If you have any question or problem, please contact Dr. Panda by email: learnwithpanda2018@gmail.com

Thank you very much and good luck with your research!

88 Replies to “Genetic Algorithm: General Concept, Matlab Code, and Example”

  1. A survey has been conducted and the data is available in Excel and want to run GA on this data. Can you please guide me how to run GA using this code?

    1. Method 1: For that problem, we can use regression to find the equation representing the relationship between input and output. After that, design GA to solve it. Method 2: Design GA to use only data in Excel (no need regression equation)

  2. Hi Mr.Panda
    Thank you for your effort .I want to know what is the type of selection, crossover and mutation you used ? and what are the constraints and optimum of this example?

    1. Hi, they are roulette wheel selection, one cut point crossover, one gene exchange mutation. This is a maximization problem

          1. In genetic algorithm after run the program Give no feasible solution how to solve this problems please

          2. Check the problem to see if any feasible solution exists, and then check your program.

  3. I’m struggling with applying Genetic/PSO/ like algo in Feature selection. Please apply them on some dataset and then use classifier to get accuracy. Waiting for code in MATLAB.

  4. I have a five parameters in my proposed method. With the means of different parameter settings, I obtained different accuracy. I want to find the best parameter setting with genetic algorithms. Can you help me in that?

    1. Step 1: find the math function of the objective function. Step 2: math equations of the constraints. Step 3: implement optimization algorithm to solve it. Good luck!

  5. Hi, Dr. Panda. Thank you for your effort. Am very impressed with this tutorial. How to do it for the minimization problem. I have one function with two variables to minimize (1% the tax of mutation and crossover tax between (60%-90%)).

  6. Thanks for your help
    I need to convert higher-order state space(11th) order to second(2nd) order state space in the h-infinity control, anything you may help me with?

  7. Hello sir
    please i need your help
    I want to optimize a metal structure or I will minimize the weight of the structure

      1. I want to implement a genetic algorithm in matlab to optimize the weight of a metal gantry and I had some difficulties. If you can give me an example and also I had a problem with the choice of coding.
        Thanks

        1. There are several GA codes in Matlab on this blog. You can customize them to solve your problems.

  8. i need to explain functional optimization using GA
    .can you suggest which example would be better

  9. can this code ga be used to calculate the minimum value of cos x and sinx with a limit of 0<x<2*pi
    multi-objective ga .
    thank you

  10. how do I solve linear mathematical equations using the genetic algorithm toolbox
    for eg. a + 2b + 3c + 4d -30
    a, b, c, and d are integer variables and interval is [0 30]

  11. Hello, I have similar problem with two variable, no constraint, one objective function. I am getting the following error message with your example. (Error: File: GA.m Line: 39 Column: 17
    Unbalanced or unexpected parenthesis or bracket.))

    Please can you share the GA.m code with me??
    Thank in advance.

  12. Hello Dr Panda,
    Thank you for sharing,
    I need to fixe the upper bound and the lower bound of the two variables in the objective functions.
    My lower and upper is fixed as -10<x<10, -10<y<10
    How to costomize this example to my case. Thank!

  13. Hi thanks for your effort and i hope if you can help me to get information on coral reef optomization (CRO) as a tool for feature selection befor using feature , code of CRO if possible.with thanks.

  14. Hi sir . Where can i download the code . I already have a membership but i don’t see where i can find the zip or file of the code

  15. hi ,first thanks for your perfemences
    i hope that you can help me in the exemple of the function f(x)=x in [0,31]
    how can use the AG to resolve it and thank you

  16. Hi,, Could you explain to me how to use this algorithm for system identification?
    i have pairs of data in excel that consist PRBS value and the Output System Value. how to implement in this code?

    1. You can modify my GA code by updating the objective function and the constraints – the rest of the code can be kept the same.

  17. Thank you, Sir. I am studying this technique to apply for Electrical machine design. I hope to accomplish whole my idea. if I could have done, I will come back here to express my appreciation again to you Sir Panda.

  18. Thanks for this Notes please if there is constraints and many variables greater than 6 how to make the genetic algorithm

  19. hi >>thanks for the great implementation .i have some kind of problem please help me .all the function work but the plot still blank after I run the GA.m

  20. Hi! I copied your Matlab codes and tried running the GA. It tells me that i do not have enough input arguments and an error in evaluation in line 5, the A equation and an error also in GA with the E equation in line 24. How do I fix it?

  21. Hello, thank you very much for your help but I didn’t get the point of the role of this two formula ? Is it a kid of “normalization” whatever ? Can you please tell me about it ?
    x=-3+A*(3-(-3))/(2^(y1/2)-1);
    y=-3+B*(3-(-3))/(2^(y1/2)-1);

  22. Sir, we request you to upload the complete Matlab code for the Genetic Algorithm with selection and GA. It would be greatly helpful to progress my research. Thank you in advance. Hopefully, waiting for your positive response.

  23. Hi sir,
    I have designed the Objective function and want to optimize the function. It is a 3 variable function and implicit in nature.
    Also want to add constraints to it. Is it possible to do with the code you have provided or have to change the code?

  24. hi sir,
    A = 1.01744032124099
    this is my final value of my work, i need the maximize of this value by using ga ,
    population size = 100,
    number of iteration = 50
    Crossover probability = 0.7
    Mutation Probability = 0.1

    1. Hello, many thanks for your interest. I don’t have GA code for your specific problems. Only thing I can do now is to suggest you to customize my GA code to solve the optimization problems in your fields.

  25. I am having a problem with bi2de I don’t know it keeps telling me it is not working can you fix it for me ? thank you

Leave a Reply

Your email address will not be published. Required fields are marked *