如何删除矩阵中的特定行

时间:2014-07-16 10:29:39

标签: matlab matrix matrix-indexing

我有一个矩阵A,我想删除具有相似值(1,1)(2,2)(3,3)

的行
A =
     1     1
     2     1
     3     1
     1     2
     2     2
     1     3
     3     3

所以矩阵就像这样

 2     1
 3     1
 1     2
 1     3

2 个答案:

答案 0 :(得分:4)

使用diff -

的一种方法
A(diff(A,[],2)~=0,:)

对于一般NXM案例,其中MA的列数,可以将其扩展为 -

A(any(diff(A,[],2)~=0,2),:)

因此,如果你有

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

你会得到 -

 2     2     3
 3     1     4
 8     1     2
 1     3     1

答案 1 :(得分:4)

另一种不调用任何函数的方法:

 A = A(A(:,1) == A(:,2),:)

此方法的效率与基于 diff()的解决方案相比:

n = 10;
y = [round(rand(n,1)) round(rand(n,1))];

tic;
for i = 1:1e4
  A = y;
  A(diff(A,[],2)~=0,:);
end
toc
Elapsed time is 0.091990 seconds.

tic;
for i = 1:1e4
  A = y;
  A = A(A(:,1) == A(:,2),:);
end
toc
Elapsed time is 0.037842 seconds.



% Suggestion of @Dan in the comments
tic;
for i = 1:1e4
  A = y;
  A(A(:,1) == A(:,2),:) = [];
end
toc
Elapsed time is 0.147636 seconds.