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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by