How to sort a table by portions of the variable names in columns

3 次查看(过去 30 天)
Hi,
I would like to ask this question in two parts...
1) Wondering how to sort this table based on the end portion of the variable name, in this case 'X??'
SM_A1_X11 SM_A1_X03 SM_B1_X10 SM_B1_X07 ...
5 10 2.5 5 ...
1 30 20 0.23 ...
....
To get this...
SM_A1_X03 SM_B1_X07 SM_B1_X10 SM_A1_X11 ...
10 5 2.5 5 ...
30 0.23 20 1 ...
....
2) Wondering how to sort this table based on the middle and then end portion of the variable name, in this case first sorting by 'A? and B?' and then 'X??'
SM_A1_X11 SM_A1_X03 SM_B1_X10 SM_B1_X07 ...
5 10 2.5 5 ...
1 30 20 0.23 ...
....
To get this...
SM_A1_X03 SM_A1_X11 SM_B1_X07 SM_B1_X10 ...
10 5 5 2.5 ...
30 1 0.23 20 ...
....
Thank you for your suggestions!

采纳的回答

Akira Agata
Akira Agata 2017-9-22
编辑:Akira Agata 2017-9-22
Regarding the 1st question, the solution will be like the following. The same method can be applied to solve the 2nd question.
% Original table
SM_A1_X11 = [5;1];
SM_A1_X03 = [10;30];
SM_B1_X10 = [2.5;20];
SM_B1_X07 = [5;0.23];
T = table(SM_A1_X11, SM_A1_X03, SM_B1_X10, SM_B1_X07);
% Extract variable names
varNames = T.Properties.VariableNames;
% Sort by 'X??'
varKey = regexprep(varNames,'SM_[\w]1_','');
[~, idx] = sort(varKey);
% Sorted table
T = T(:,idx);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by