Finding matching rows in matrix for multiple points without a loop
2 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Stephen23
on 9 Apr 2015
Edited: Stephen23
on 9 Apr 2015
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];
>> [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 Comments
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!