我使用matlab,我有一个矩阵
1 1
2 1
3 1
4 2
5 2
6 2
7 1
8 1
9 2
10 2
11 2
如何从第二列复制矩阵但只能复制一定数量?另一个数字将是随机的1或2.示例
1 1 1 | | 1 1 1
2 1 1 | | 2 1 1
3 1 1 | | 3 1 1
4 2 2 | | 4 2 2
5 2 1 | OR | 5 2 2
6 2 1 | | 6 2 1
7 1 1 | | 7 1 1
8 1 1 | | 8 1 1
9 2 2 | | 9 2 2
10 2 2 | |10 2 1
11 2 1 | |11 2 1
如果2的第3行变为1,则列的其余部分将变为1.处理重复,直到达到另一组2
答案 0 :(得分:0)
您可以使用逻辑索引和函数randi
:
a = [1 1;
2 1;
3 1;
4 2;
5 2;
6 2;
7 1;
8 1;
9 2;
10 2;
11 2];
b = randi(2,length(a),1); %generation of random value ∈ [1,2]
b(a(:,2)==1) = 1; %if a(:,2) = 1 b = 1;
a = [a,b]
答案 1 :(得分:0)
A= [1 1
2 1
1 1
4 2
5 2
6 2
7 1
8 1
9 2
10 2
11 2] ;
colLength = length (A(:,1)) ;
thridcol = randi (2,colLength,1)
A(:,3) = thridcol ;
flag = 1 ;
i = 1 ; ;
if ( sum (A(3,:) == 1) == length (A(2,:)))
while (flag && i < colLength)
A(3+i,3 ) = 1 ;
if (sum (A(3+i,:) == 2) == length (A(3+i,:)))
flag = 0 ;
end
i = i +1 ;
end
end