Search code examples
matlabgenetic-algorithmcrossover

Two point crossover in Matlab


What is the best way to implement two point crossover in Matlab? The two point crossover is described here. Note that in my application I cannot split the lists wherever. They are grouped by four, so places where it is allowed to split a list (chromosome) is 4, 8, 12 and so on (this is because my application is a linear genetic programming problem).

I tried this, but it doesn't work as sometimes I get chromosomes that have a number of elements which is not evenly divisible by four. I need help figuring out how to make it work.

function newPopulation = Crossover( population, p )

newPopulation = population;

for i=1:2:length(population)
    if p < rand
        [newPopulation{i}, newPopulation{i+1}] = PerformCrossover( newPopulation{i}, newPopulation{i+1} );
    end
end

end

function [newChromosome1, newChromosome2] = PerformCrossover( c1, c2 )
    l1 = length(c1)/4;
    l2 = length(c2)/4;

    i1 = 4*sort( randperm( l1, 2 ) )-[3 4];
    i2 = 4*sort( randperm( l2, 2 ) )-[3 4];

    newChromosome1 = [ c1( 1:l1<i1(1) ) c2( i2(1):i2(2) ) c1( 1:l1>i1(2) ) ];
    newChromosome2 = [ c2( 1:l2<i2(1) ) c1( i1(1):i1(2) ) c2( 1:l2>i2(2) ) ];
end

EDIT. There seems to be confusion. I want the version of crossover that is described by my code. In this code the segments from each chromosome do not have the same length. This means that I change the size of the chromosomes when I do the swap, this is intended. Further explanation is available in the comment to McMa.


Solution

  • leave everything as is, as it is already optimized, and correct this:

    i1 = 4*sort( randperm( l1, 2 ) )-[3 3];
    i2 = 4*sort( randperm( l2, 2 ) )-[3 3];
    
    newChromosome1 = [ c1( 1:i1(1) ) c2( i2(1)+1:i2(2)-1 ) c1( i1(2):end ) ];
    newChromosome2 = [ c2( 1:i2(1) ) c1( i1(1)+1:i1(2)-1 ) c2( i2(2):end ) ];