Finding matching rows in matrix for multiple points without a loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Matthew
am 9 Apr. 2015
Bearbeitet: Stephen23
am 9 Apr. 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.
0 Kommentare
Akzeptierte Antwort
Stephen23
am 9 Apr. 2015
Bearbeitet: Stephen23
am 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!