Finding matching rows in matrix for multiple points without a loop

조회 수: 2 (최근 30일)
Matthew
Matthew 2015년 4월 9일
편집: Stephen23 2015년 4월 9일
I have matrix
A=[1 2 3;4 5 6;7 8 9;9 8 7;6 5 4;3 2 1]
B=[4 5 6; 3 2 1]
test = [2 6]
I want to be able to list the index of A where there is an exact matching row, in the same order for each line in B. I can find this value for one row at a time, but i am looking for a way to do search A for each row of B, without a loop.
test=find(ismember(A,B(1,1:3),'rows'),1)
I may also want to change the values in A to "zeros"
Thank you.

채택된 답변

Stephen23
Stephen23 2015년 4월 9일
편집: Stephen23 2015년 4월 9일
This can be achieved using sortrows and sort together with some basic MATLAB indexing. First we define the test-data (I added one non-matching row to B):
>> A = [1,2,3;4,5,6;7,8,9;9,8,7;6,5,4;3,2,1];
>> B = [4,5,6;3,2,1;0,0,0];
Then we determine any matching rows using sortrows and a simple element-wise equality:
>> [C,D] = sortrows([A;B]);
>> E = all(C(1:end-1,:)==C(2:end,:),2);
>> F = D(E)
F =
6
2
>> A(F,:)
ans =
3 2 1
4 5 6
But these are in the order that they occur in A. To get the order that they occur in B, we can do this:
>> [~,X] = sort(D([false;E]));
>> F(X)
ans =
2
6
>> A(F(X),:)
ans =
4 5 6
3 2 1

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by