繁体   English   中英

Matlab中遗传算法交叉的代码

[英]Code for Genetic Algorithm Cross-Over in Matlab

假设我有两个Parents行。

父母1:3-1-2-5-4
父母2:1-4-5-2-3

现在,在交叉之后,我要具有以下子行:

儿童1:1-4- | 2-5 | -3
儿童2:3-1- | 5-2 | -4

单个位置交叉点用“ |”表示。 请给我上面的子序列的代码。

采用:

%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);

结果:

child1 =

 3     1     5     2     4

child2 =

 1     4     2     5     3

在此代码段中,将rowToSwap确定为硬编码。 如果需要,可以使用randsample函数随机选择它们:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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