Find element in matrix

조회 수: 50 (최근 30일)
Eduardo
Eduardo 2012년 4월 3일
Hello, I have a matrice and i whant to find if there are 2 iqual elements in diferent rows...
A =
1 2
3 5
2 4
6 1
In this case i should find the number 1 and 2. But i whant to find one at a time. Can someone help me with this? Thank´s.
  댓글 수: 1
Image Analyst
Image Analyst 2012년 4월 6일
A is comprised on ONLY integers, right? Else you need to consider the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F

댓글을 달려면 로그인하십시오.

채택된 답변

Richard Brown
Richard Brown 2012년 4월 11일
Here's a slightly uglier way that will work. If you need the code to perform quickly, you'd obviously preallocate your arrays m and z
z = zeros(0, 2);
m = [];
for a = unique(A(:)');
[I, ~] = find(A == a);
if numel(I) == 2
m = [m a];
z = [z; setdiff(reshape(A(I, :), 1, 4), a)];
end
end
  댓글 수: 1
Eduardo
Eduardo 2012년 4월 16일
Thank´s a lot.

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

Thomas
Thomas 2012년 4월 3일
A = [1 2
3 5
2 4
6 1 ];
intersect(A(:,1),A(:,2))
  댓글 수: 1
Sean de Wolski
Sean de Wolski 2012년 4월 3일
or ismember()

댓글을 달려면 로그인하십시오.


Thomas
Thomas 2012년 4월 6일
Try this
clear all
A = [1 2
3 5
2 4
6 1 ];
c=intersect(A(:,1),A(:,2));
for i=1:length(c)
[p(:,:),q(:,:)]=find(A==c(i));
l=A(p(:),:);
m=unique(l)';
z(i,:)=m(m~=c(i));
end
c % common elements 1 and 2
z % elements associated with 1=2,6 and 2=1,4
Output will be
c =
1.00
2.00
z =
2.00 6.00
1.00 4.00
  댓글 수: 1
Eduardo
Eduardo 2012년 4월 11일
First of all, thanks.
It works only in some cases... In the case of the same element be on the same row but diferent lines, with this code can´t be found... Any idea?

댓글을 달려면 로그인하십시오.


Eduardo
Eduardo 2012년 4월 6일
Thank´s... What i need is something more complex, but i didn´t explain it... If i find 2 iqual elements like number 1, for example, what i need to do is connect the other elements in the same line. If i find 1 in to lines ([1 2] and [6 1]) what i need to do is create a new line with [2 6]. I don´t know how to do it...

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by