我有一个矩阵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
答案 0 :(得分:4)
使用diff
-
A(diff(A,[],2)~=0,:)
对于一般NXM
案例,其中M
是A
的列数,可以将其扩展为 -
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.