2017-10-29 71 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。 –

相關問題