A concise way to sort the rows of matrix A in the same order of the rows of matrix B

1 view (last 30 days)
Hi, do you know a way to sort the rows of matrix A in the same order of the rows of matrix B, but in a more concise way/code as I did (e.g. without a loop for)?
P.S.: bear in mind that (i) only the first two columns of A are used for the sorting, and that (ii) sometimes elements of the first two columns of A are switched when compared to B (i.e. in a certain row, the number in the first column, in A, is the number in the second column, in B, and viceversa), e.g. "6128 2269" in A corresponds to "2269 6128" in B.
A = [ 3358 6128 0 0 30 37 42 30
5945 6128 21 21 36 42 49 35
5945 7505 0 0 31 37 41 30
6128 2269 20 20 34 41 47 33
7120 2269 26 25 42 51 58 42];
B = [ 2269 6128
2269 7120
3358 6128
5945 6128
5945 7505];
[~,id1] = ismember(A(:,[1 2]),B,'rows');
[~,id2] = ismember(A(:,[2 1]),B,'rows');
id3 = [id1 id2];
for i = 1 : size(B,1)
[id4,~] = find(id3==i);
C(i,:) = A(id4,:);
end
% result
C =
6128 2269 20 20 34 41 47 33
7120 2269 26 25 42 51 58 42
3358 6128 0 0 30 37 42 30
5945 6128 21 21 36 42 49 35
5945 7505 0 0 31 37 41 30

Accepted Answer

Cris LaPierre
Cris LaPierre on 27 Jan 2022
I think you have a good approach considering that any permutation of the 2 columns is considered equal. However, you can just use indexing to create C. No need to loop through everything.
Another option might be to sum the two columns of A and B, but that isn't any more succinct.
A = [ 3358 6128 0 0 30 37 42 30
5945 6128 21 21 36 42 49 35
5945 7505 0 0 31 37 41 30
6128 2269 20 20 34 41 47 33
7120 2269 26 25 42 51 58 42];
B = [ 2269 6128
2269 7120
3358 6128
5945 6128
5945 7505];
[~,id1] = ismember(B,A(:,[1 2]),'rows');
[~,id2] = ismember(B,A(:,[2 1]),'rows');
id3 = id1+id2;
id3 = 5×1
4 5 1 2 3
C = A(id3,:)
C = 5×8
6128 2269 20 20 34 41 47 33 7120 2269 26 25 42 51 58 42 3358 6128 0 0 30 37 42 30 5945 6128 21 21 36 42 49 35 5945 7505 0 0 31 37 41 30

More Answers (0)

Community Treasure Hunt

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

Start Hunting!