如何在matlab中对两个矩阵进行单点交叉

How to make single point crossover between two matrix in matlab

我需要使用单点交叉对任意两个矩阵进行交叉。 Matlab 中的代码是什么?

n=input('no.of ROWS AND COLUMNS');
sm_mat = eye(n);
for i=1:n
    temp = randperm(n);
    fprintf('Initial Population %d\n',i)
    eval(['sm_mat_', num2str(i) '=sm_mat(:,temp)']);
end

如果我理解正确你的问题是什么,你可以轻松地手动完成 One-Point 交叉。所以你确实想创建 n 可能的 parents,随机 select 其中两个,然后在它们的行之间执行交叉以创建一个新的个体 (child) .

而不是为每个(候选)parent 创建不同的变量(这将使这两个 parent 的随机 selection 变得非常困难)我建议你创建一个具有 n 个单元格的单元格数组,其中 i-th 单元格将包含 i-th 矩阵(候选 parent)。

n=input('no.of ROWS AND COLUMNS');
sm_mat = eye(n);
for i=1:n
    temp = randperm(n);
%     fprintf('Initial Population %d\n',i)
%     eval(['sm_mat_', num2str(i) '=sm_mat(:,temp)']);
    InitialPopCell{i}=sm_mat(:,temp);
end

InitialPopCell 将是我们的元胞数组。
现在您需要随机 select 两个 parent:为此,您只需随机 select 两个不同的单元格即可。

i=0; j=0;
while i==j
    i=randi(n);
    j=randi(n);
end

以这种方式,我们 select 两个索引(ij)考虑到它们必须在 [1:n] 范围内并且它们必须不同于每个其他.
现在我们可以 select 两个 parents:

ParentA=InitialPopCell{i};
ParentB=InitialPopCell{j};
Child=[]; 

我们还将 Child(即新个体)矩阵初始化为空。
现在,最后,让我们进行交叉:

for i=1:size(ParentA,1)
    % select random integer between 1 and the number of chromosomes
    % this will be the crossover point
    XOverPoint=randi(size(ParentA,2));

    % create new individual by concatenating Parent A and B taking into
    % account the crossover point
    Child(i,:)=[ParentA(i,1:XOverPoint) ParentB(i,XOverPoint+1:end)];
end