Find equal elements between two matrices

조회 수: 12 (최근 30일)
Paschalis Garouniatis
Paschalis Garouniatis 2016년 7월 3일
댓글: Paschalis Garouniatis 2016년 7월 3일
Greetings everyone. I have two matrices (x,y data) which have different size (1044x2 and 952x2). I want to find the elements (all from the first column, x data) that co-exist in them. Then I will create two new matrices where the first column will consist of those elements and the second column will consist of the y data from each former matrix that correspond to the elements mentioned. Below I have included the code that I used which resulted to only one (the last) element which is same for both. My mistake is that the variables MyMatrix3 and MyMatrix4 are not stated as matrices and so the result is what it should be expected. I am a bit confused about how to state them as matrices. Any help? Thanks in advance.
for i=1:length(MyMatrix1)
for j=1:length(MyMatrix2)
if (MyMatrix1(i,1)==MyMatrix2(j,1))
MyMatrix3=[MyMatrix1(i,1) MyMatrix1(i,2)];
MyMatrix4=[MyMatrix2(j,1) MyMatrix2(j,2)];
end
end
end
  댓글 수: 2
dpb
dpb 2016년 7월 3일
"create two new matrices where ... the second column will consist of the y data from each former matrix that correspond to the elements mentioned."
Huh??? What does this mean, precisely? Give a short example dataset with the input, desired output, and rules by which the latter was obtained from the former.
I'm guessing all you really need is the outputs from
ismember(A(:,1), B(:,1))
but need an example to clarify what it is you really want. Can undoubtedly be as short as 5 or 6 elements to illustrate.
Paschalis Garouniatis
Paschalis Garouniatis 2016년 7월 3일
편집: Paschalis Garouniatis 2016년 7월 3일
Thanks a lot for your response dpb. Let's say that I have 2 matrices: a=[4 3;1 2;10 11;5 7] and b=[1 3;10 21;6 6;3 7]. I want to create two new matrices which will have same first column and the second column will be the one that corresponds to the former matrix. So the matrices I want to create would be: c=[1 2;10 11] and d=[1 3;10 21].

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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 7월 3일
편집: Andrei Bobrov 2016년 7월 3일
a=[4 3;1 2;10 11;5 7] , b=[1 3;10 21;6 6;3 7];
[lo , ii] = ismember(a(:,1),b(:,1));
out = {a(lo,:), b(ii(lo),:)};
or
ij = bsxfun(@eq,a(:,1),b(:,1)');
out = {a(any(ij,2),:), b(any(ij),:)};
  댓글 수: 1
Paschalis Garouniatis
Paschalis Garouniatis 2016년 7월 3일
Andrei thanks a lot for your response. It worked just fine!

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by