How to sort one array based on another of a different size

11 ビュー (過去 30 日間)
rbrbrb
rbrbrb 2020 年 6 月 23 日
編集済み: Stephen23 2020 年 6 月 24 日
Hello,
I would like to sort one cell array A according to the order define by a separate cell array B of a smaller size. For example:
A = [a a b c c d d d d e e]
B = [d a c b e]
After sorting, array A would be:
A = [d d d d a a c c b e e]
Thank you for the help.
  1 件のコメント
Rik
Rik 2020 年 6 月 23 日
I would write code that replaced every value in your top array by the index in your second array. Then you can sort and use indexing to get the original values back.

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

採用された回答

Stephen23
Stephen23 2020 年 6 月 24 日
編集済み: Stephen23 2020 年 6 月 24 日
As Rik wrote, the MATLAB solution is to use ismember, e.g.:
>> A = {'a','a','b','c','c','d','d','d','d','e','e'};
>> B = {'d','a','c','b','e'};
>> [X,Y] = ismember(A,B);
>> [~,Z] = sort(Y(X));
>> C = A(Z)
C =
'd' 'd' 'd' 'd' 'a' 'a' 'c' 'c' 'b' 'e' 'e'

その他の回答 (1 件)

Aakash Mehta
Aakash Mehta 2020 年 6 月 23 日
編集済み: Aakash Mehta 2020 年 6 月 23 日
A = ['a' 'a' 'b' 'c' 'c' 'd' 'd' 'd' 'd' 'e' 'e']
B = ['d' 'a' 'c' 'b' 'e']
sizeA = length(A)
sizeB = length(B)
You can use the container.Map to track the frequency of the characters. This approach will also work when A is not sorted.
M = containers.Map
for i=1:sizeA
if isKey(M,A(i))==1
M(A(i)) = M(A(i)) + 1;
else
M(A(i)) = 1;
end
end
You will get the map M, which contains the characters as a key and frequency as their value.
Now using following code you can get the desired output.
str = "";
for i=1:sizeB
if isKey(M,B(i))==1
for j=1:M(B(i))
str = strcat(str,B(i));
end
end
end
  1 件のコメント
Rik
Rik 2020 年 6 月 23 日
I suspect this can be vectorized with ismember. I suspect that the mapping you are proposing has a lot of unnecessary overhead.

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

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by