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

2 ビュー (過去 30 日間)
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

採用された回答

Cris LaPierre
Cris LaPierre 2022 年 1 月 27 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWaveform Generation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by