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

2 Ansichten (letzte 30 Tage)
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!

Akzeptierte Antwort

Akira Agata
Akira Agata am 22 Sep. 2017
Bearbeitet: Akira Agata am 22 Sep. 2017
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);

Weitere Antworten (0)

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by