Paste a genetic algorithm to be useful to some people

Source: Internet
Author: User
Tags binary to decimal

% Percent %
% Percent %
%
% Calculate the maximum value of the following functions %
% F (x) = 10 * sin (5x) + 7 * cos (4x) x ε [0, 10] %
% The value of x is expressed as a binary value in the form of a 10-bit binary value. %
%
% Percent %
% Percent %

% Programming
% -----------------------------------------------
% 2.1 initialization (encoding)
The % initpop. m function is used to initialize a group. popsize indicates the group size, and chromlength indicates the length of the chromosome (length of a binary number ),
The length of % depends on the length of the variable's binary code (10 digits in this example ).
% Genetic algorithm subroutine
% Name: initpop. m
% Initialization
Function pop = initpop (popsize, chromlength)
Pop = round (rand (popsize, chromlength); % rand randomly generates a matrix with the number of rows being {0, 1} and the number of columns being chromlength,
% Roud round each unit of the matrix. The initial population.

% 2.2 calculate the target function value
% 2.2.1 convert binary to decimal (1)
% Genetic algorithm subroutine
% Name: decodebinary. m
% Generates the row vector [2 ^ n 2 ^ (n-1)... 1], then sums and converts the binary into decimal.
Function pop2 = decodebinary (pop)
[Px, py] = size (pop); % evaluate the number of pop rows and Examples
For I = 1: py
Pop1 (:, I) = 2. ^ (py-1). * pop (:, I );
Py = py-1;
End
Pop2 = sum (pop1, 2); % calculates the sum of each row of pop1

% 2.2.2 convert binary encoding to decimal number (2)
The % decodechrom. m function is used to convert the chromosome (or binary code) to decimal. The spoint parameter indicates the starting position of the binary string to be decoded.
% (For multiple variables, if there are two variables, expressed as 20, each variable 10 is, the first variable starts from 1, and the other variable starts from 11. In this example, 1 ),
% The 1ength parameter indicates the intercepted length (10 in this example ).
% Genetic algorithm subroutine
% Name: decodechrom. m
% Convert binary encoding to decimal
Function pop2 = decodechrom (pop, spoint, length)
Pop1 = pop (:, spoint: spoint + length-1 );
Pop2 = decodebinary (pop1 );

% 2.2.3 calculate the target function value
The % calobjvalue. m function is used to calculate the target function. The formula is simulated using the example in this article and can be modified based on different optimization problems.
% Genetic algorithm subroutine
% Name: calobjvalue. m
% Implement the calculation of the target function
Function [objvalue] = calobjvalue (pop)
Temp1 = decodechrom (pop,); % convert each pop row to a decimal number
X = temp1 * 10/1023; % convert the number in the binary value field to the number in the variable Field
Objvalue = 10 * sin (5 * x) + 7 * cos (4 * x); % calculate the target function value

% 2.3 calculate the adaptive value of an individual
% Genetic algorithm subroutine
% Name: calfitvalue. m
% Calculate the adaptive value of an individual
Function fitvalue = calfitvalue (objvalue)
Global Cmin;
Cmin = 0;
[Px, py] = size (objvalue );
For I = 1: px
If objvalue (I) + Cmin> 0
Temp = Cmin + objvalue (I );
Else
Temp = 0.0;
End
Fitvalue (I) = temp;
End
Fitvalue = fitvalue ';

% 2.4 select copy
% The select or copy operation determines which individuals can enter the next generation. This method is easy to implement by using the gambling Wheel Selection Method in the program.
% According to the equation pi = fi/Σ fi = fi/fsum, select the step:
% 1) in the t generation, the (1) formula calculates fsum and pi
% 2) generate the random number rand (.) of {}, and evaluate s = rand (.) * fsum
% 3) Calculate the minimum k in Σ fi ≥s, then the k-th individual is selected
% 4) perform N operations (2) and 3) to obtain N individuals and form the population of generation t = t + 1.
% Genetic algorithm subroutine
% Name: selection. m
% Select copy
Function [newpop] = selection (pop, fitvalue)
Totalfit = sum (fitvalue); % calculate the sum of the adaptive values
Fitvalue = fitvalue/totalfit; % probability of individual being selected
Fitvalue = cumsum (fitvalue); % if fitvalue = [1 2 3 4], then cumsum (fitvalue) = [1 3 6 10]
[Px, py] = size (pop );
MS = sort (rand (px, 1); % arranged in ascending order
Fitin = 1;
Newin = 1;
While newin <= px
If (MS (newin) newpop (newin, :) = pop (fitin ,:);
Newin = newin + 1;
Else
Fitin = fitin + 1;
End
End

% 2.5 cross
% Crossover (crossover). Each individual in a group crosses PCs with a certain probability, that is, two individuals are located at a certain position in their respective strings.
% (Usually randomly determined) begins to exchange with each other, which is similar to the genetic split and reorganization during biological evolution. For example, assume that there are two parent generations x1, and x2 is:
% X1 = 0100110
% X2 = 1010001
% Starting from the 1st bit of each individual, after the intersection, two new child instances y1 and y2 are obtained:
% Y1 = 0100001
% Y2 = 1010110
% In this way, the two child instances have some characteristics of the two parent generations respectively. With the help of transactions, we may combine the parent generation into a higher degree of attention in the child generation.
% In fact, intersection is one of the main features of genetic algorithms that distinguish it from other traditional optimization methods.
% Genetic algorithm subroutine
% Name: crossover. m
% Cross
Function [newpop] = crossover (pop, pc)
[Px, py] = size (pop );
Newpop = ones (size (pop ));
For I = 1: 2: px-1
If (rand cpoint = round (rand * py );
Newpop (I, :) = [pop (I, 1: cpoint) pop (I + 1, cpoint + 1: py)];
Newpop (I + 1, :) = [pop (I + 1, 1: cpoint) pop (I, cpoint + 1: py)];
Else
Newpop (I, :) = pop (I ,:);
Newpop (I + 1, :) = pop (I + 1 ,:);
End
End

% 2.6 Variation
% Mutation (mutation), a genetic mutation is generally present in the biological evolution process. Mutation means that each individual in the parent generation is flipped by the probability pm, that is, from "1" to "0 ",
% Or changed from "0" to "1 ". The mutation feature of the genetic algorithm allows the solution process to randomly search for the entire space where the solution may exist. Therefore, the global optimal solution can be obtained to a certain extent.
% Genetic algorithm subroutine
% Name: mutation. m
% Variation
Function [newpop] = mutation (pop, pm)
[Px, py] = size (pop );
Newpop = ones (size (pop ));
For I = 1: px
If (rand mpoint = round (rand * py );
If mpoint <= 0
Mpoint = 1;
End
Newpop (I, :) = pop (I ,:);
If any (newpop (I, mpoint) = 0
Newpop (I, mpoint) = 1;
Else
Newpop (I, mpoint) = 0;
End
Else
Newpop (I, :) = pop (I ,:);
End
End

% 2.7 find the largest adaptive value of a group and its individual
% Genetic algorithm subroutine
% Name: best. m
% Find the maximum adaptive value in the group
Function [bestindividual, bestfit] = best (pop, fitvalue)
[Px, py] = size (pop );
Bestindividual = pop (1 ,:);
Bestfit = fitvalue (1 );
For I = 2: px
If fitvalue (I)> bestfit
Bestindividual = pop (I ,:);
Bestfit = fitvalue (I );
End
End

% 2.8 main program
% Main program of Genetic Algorithm
% Name: genmain05.m
Clear
Clf
Popsize = 20; % group size
Chromlength = 10; % string length (individual length)
Pc = 0.6; % crossover probability
Pm = 0.001; % mutation probability

Pop = initpop (popsize, chromlength); % randomly generate the initial group
For I = % 20 indicates the number of iterations.
[Objvalue] = calobjvalue (pop); % calculate the target function
Fitvalue = calfitvalue (objvalue); % calculate the fitness of each individual in the group
[Newpop] = selection (pop, fitvalue); % copy
[Newpop] = crossover (pop, pc); % cross
[Newpop] = mutation (POP, PC); % mutation
[Bestindividual, bestfit] = Best (POP, fitvalue); % find the individuals with the largest adaptive value in the group and their adaptive values
Y (I) = max (bestfit );
N (I) = I;
Pop5 = bestindividual;
X (I) = decodechrom (pop5, 1, chromlength) * 10/1023;
Pop = newpop;
End

Fplot ('10 * sin (5 * x) + 7 * Cos (4 * X) ', [0 10])
Hold on
Plot (X, Y, 'r *')
Hold off

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.