简体   繁体   中英

Code for Genetic Algorithm Cross-Over in Matlab

Let suppose I have two Parents rows.

parent 1: 3-1-2-5-4
parent 2: 1-4-5-2-3

Now after Cross-Over, I want to have following child rows:

Child 1: 1-4-|2-5|-3
Child 2: 3-1-|5-2|-4

A single position cross-Over is denoted by "|". Kindly if there is any code that gives me the above child sequences.

Use:

%initilizes parents
parent1 = [3 1 2 5 4];
parent2 = [1 4 5 2 3];

%determines which rows should be swapped
rowsToSwap = [3 4];

%generates child1 and child2
child1 = parent2;
child1(rowsToSwap) = parent1(rowsToSwap);
child2 = parent1;
child2(rowsToSwap) = parent2(rowsToSwap);

Results:

child1 =

 3     1     5     2     4

child2 =

 1     4     2     5     3

In this code snippet, rowsToSwap are determined hard-codded. if you want, you can choose them randomly by using randsample function:

rowsToSwap = randsample(1:length(parent1),2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM