我正在做一个遗传算法,我正在测试我如何从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
谢谢
答案 0 :(得分: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