How to sort one array based on the order of a second array?

1 ビュー (過去 30 日間)
David Mabwa
David Mabwa 2021 年 1 月 22 日
コメント済み: David Mabwa 2021 年 1 月 22 日
Hi,
This seems like a very simple problem, but I can't seem to get it to work with the answers already available.
I have 2 string arrays:
A=["1a","1b","1c","1d","1e","2a","2b","2c","2d","2e"];
B=["A1_2a","U1_1c","Z1_2d","I1_1e","T1_1a","F1_2b","O1_1d","P1_2c","J1_2e","S1_1b"];
Let's say A is a newly sorted array from a previously disordered array (e.g. Q=["1c","2a","1e","2d","1b","2c","2e","1a","2b","1d"];)
How do I sort B, based on how Q was sorted?
The goal is to produce the array below
C=["T1_1a","S1_1b","U1_1c","O1_1d","I1_1e","A1_2a","F1_2b","P1_2c","Z1_2d","J1_2e"];
Thanks in advance.

採用された回答

Stephen23
Stephen23 2021 年 1 月 22 日
As far as I can tell, the order of Q is irrelevant.
A = ["1a","1b","1c","1d","1e","2a","2b","2c","2d","2e"]; % sorted
B = ["A1_2a","U1_1c","Z1_2d","I1_1e","T1_1a","F1_2b","O1_1d","P1_2c","J1_2e","S1_1b"];
[~,X] = ismember(A,extractAfter(B,'_'));
C = B(X)
C = 1×10 string array
"T1_1a" "S1_1b" "U1_1c" "O1_1d" "I1_1e" "A1_2a" "F1_2b" "P1_2c" "Z1_2d" "J1_2e"
  1 件のコメント
David Mabwa
David Mabwa 2021 年 1 月 22 日
Thanks a lot. This is exactly what I needed. Much appreciated @Stephen Cobeldick

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by