Sort Matlab table based on pre-defined order

I would like to sort a table based on a column that only contains 4 string values (A, B, C, and d) in an specific order that is not alphabetic.
This is what I am currently using:
sortrows(table_1,{'col1','col2'},{'ascend' 'descend'})
For col2 I would like to use a custom order that is neither ascend nor descend. So for instance the sorting order should be:
B
A
C
D

 採用された回答

Stephen23
Stephen23 2022 年 1 月 31 日
編集済み: Stephen23 2022 年 1 月 31 日

0 投票

You could do something like this, where C is that column:
D = {'B';'A';'C';'D'}; % the desired order
C = {'C';'C';'A';'D';'B';'C';'A';'D';'B'} % the column to sort
C = 9×1 cell array
{'C'} {'C'} {'A'} {'D'} {'B'} {'C'} {'A'} {'D'} {'B'}
[X,Y] = ismember(C,D);
[~,Z] = sort(Y);
D = C(Z) % of course you would sort the table e.g. T(Z,:)
D = 9×1 cell array
{'B'} {'B'} {'A'} {'A'} {'C'} {'C'} {'C'} {'D'} {'D'}

1 件のコメント

Metin Akyol
Metin Akyol 2022 年 1 月 31 日
Thank you, worked very well.

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

その他の回答 (1 件)

Turlough Hughes
Turlough Hughes 2022 年 1 月 31 日

0 投票

Try the following:
idx = [2 1 3 4];
T(idx,:) = T

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

製品

リリース

R2021a

タグ

質問済み:

2022 年 1 月 31 日

コメント済み:

2022 年 1 月 31 日

Community Treasure Hunt

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

Start Hunting!

Translated by