2017-10-29 37 views
0

我正在做一个遗传算法,我正在测试如何从R创建后代,每行R对应一个父项,每列对应一个特征。在我的代码中,我试图让父母1和2以及父母3和4交配,总共给了两个孩子。但是,当我运行代码时,它会在子1和子2之间插入额外的零行。为什么发生这种情况?为什么在我的矩阵中显示额外的一行?

R=[1,2,3;4,5,6;1000,2000,3000;4000,5000,6000] 
for parent=1:2:3 
    theta=rand(1); 
    trait1=theta*R(0+parent,1)+(1-theta)*R(1+parent,1); 
    theta=rand(1); 
    trait2=theta*R(0+parent,2)+(1-theta)*R(1+parent,2); 
    theta=rand(1); 
    trait3=theta*R(0+parent,3)+(1-theta)*R(1+parent,3); 

    children(parent,:)=[trait1,trait2,trait3]; 
end 
children 

输出:

R = 

      1   2   3 
      4   5   6 
     1000  2000  3000 
     4000  5000  6000 


children = 

    3.0837e+00 4.2959e+00 3.2356e+00 
      0   0   0 
    2.7330e+03 2.7728e+03 3.0762e+03 

谢谢

回答

1

parent变量上循环的第一步等于1,在第二台阶等于3。所以你有行1和3填充。 添加另一个迭代变量保存在children结果,或只是追加行这样的:

R=[1,2,3;4,5,6;1000,2000,3000;4000,5000,6000] 
children = []; 
for parent=1:2:3 
    theta=rand(1); 
    trait1=theta*R(0+parent,1)+(1-theta)*R(1+parent,1); 
    theta=rand(1); 
    trait2=theta*R(0+parent,2)+(1-theta)*R(1+parent,2); 
    theta=rand(1); 
    trait3=theta*R(0+parent,3)+(1-theta)*R(1+parent,3); 

    children=[children;trait1,trait2,trait3]; 
end 
children 

与阵列和迭代变量的预定义大小的另一种选择:

R=[1,2,3;4,5,6;1000,2000,3000;4000,5000,6000] 
children = zeros (2,3); 
i = 1; 
for parent=1:2:3 
    theta=rand(1); 
    trait1=theta*R(0+parent,1)+(1-theta)*R(1+parent,1); 
    theta=rand(1); 
    trait2=theta*R(0+parent,2)+(1-theta)*R(1+parent,2); 
    theta=rand(1); 
    trait3=theta*R(0+parent,3)+(1-theta)*R(1+parent,3); 

    children(i,:)=[trait1,trait2,trait3]; 
    i = i + 1; 

end 
children 
+0

追加从来都不是一个好主意,如果你是要继续做下去 –

+0

@SardarUsama我们是否谈论优化?在初始代码中,每个迭代中“子女”的大小都在变化。但我同意,在任何情况下,数组的大小是已知的,最好明确地定义它。只是不确定为什么这个主题有2行很重要。无论如何,更新了我的答案。 –

+0

一个问题是为了成为一个MCVE。 –

相关问题