通过固定的给定行查找并替换具有重复数字的数组的行

时间:2014-12-14 20:21:58

标签: matlab matrix row

我有一个矩阵,其中包含重复数字的行。我想找到那些行并用虚拟行替换它们,以便保持矩阵的行数不变。

Dummy_row = [1 2 3]

(5x3)矩阵A

A = [2 3 6;
     4 7 4;
     8 7 2;
     1 3 1;
     7 8 2]

(5x3)Matrix new_A

new_A = [2 3 6;
         1 2 3;
         8 7 2;
         1 2 3;
         7 8 2]

我尝试了以下删除了具有重复数字的行。

y = [1 2 3]
w = sort(A,2)
v = all(diff(t,1,2)~=0|w(:,1:2)==0,2)  %  When v is zero, the row has repeated numbers
z = A(w,:)

你能帮忙吗?

3 个答案:

答案 0 :(得分:3)

看看这是否适合您,

A= [ 2 3 6;
     4 7 4;
     8 7 2;
     5 5 5;
     1 8 8;
     1 3 1;
     7 8 2 ];
Dummy_row = [1 2 3];
b = diff(sort(A,2),1,2);
b = sum(b == 0,2);
b = b > 0;
c = repmat(Dummy_row,sum(b),1);
b = b' .* (1:length(b));
b = b(b > 0);
newA = A; 
newA(b,:) = c;

给出,

newA =
 2     3     6
 1     2     3
 8     7     2
 1     2     3
 1     2     3
 1     2     3
 7     8     2

修改

不需要做太多改变,试试这个,

Dummy_row = [1 2 3];
b = sum(A == 0,2);
b = b > 0;
c = repmat(Dummy_row,sum(b),1);
b = b' .* (1:length(b));
b = b(b > 0); 
newA = A; 
newA(b,:) = c;

答案 1 :(得分:3)

基于

bsxfun的解决方案 -

%// Create a row mask of the elements that are to be edited
mask = any(sum(bsxfun(@eq,A,permute(A,[1 3 2])),2)>1,3);

%// Setup output variable and set to-be-edited rows as copies of [1 2 3]
new_A = A;
new_A(mask,:) = repmat(Dummy_row,sum(mask),1)

代码运行 -

A =
     2     3     6
     4     7     4
     8     7     2
     1     3     1
     7     8     2
new_A =
     2     3     6
     1     2     3
     8     7     2
     1     2     3
     7     8     2

答案 2 :(得分:3)

您可以使用以下内容:

hasRepeatingNums = any(diff(sort(A, 2), 1, 2)==0, 2); 
A(hasRepeatingNums,:) = repmat(Dummy_row, nnz(hasRepeatingNums), 1);