Finding matching rows in matrix for multiple points without a loop

6 vues (au cours des 30 derniers jours)
Matthew
Matthew le 9 Avr 2015
Modifié(e) : Stephen23 le 9 Avr 2015
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.

Réponse acceptée

Stephen23
Stephen23 le 9 Avr 2015
Modifié(e) : Stephen23 le 9 Avr 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];
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

Plus de réponses (0)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by