Sort rows of a table by column within a variable
3 views (last 30 days)
Show older comments
J AI
on 28 Jul 2020
Answered: Eric Sofen
on 12 Mar 2024
I have a table:
T =
a v
________ _______________________________
0.88517 0.33536 0.65376 0.89092
0.91329 0.67973 0.49417 0.33416
0.79618 0.13655 0.77905 0.69875
0.098712 0.72123 0.71504 0.19781
0.26187 0.10676 0.90372 0.030541
I want to sort the table using the last column of v. This is the closest I could find but obviously it does not work (thus I am posting the question):
sortedT = sortrows(T,'v')
I am not sure how it sorts in this case:
sortedT =
a v
________ _______________________________
0.26187 0.10676 0.90372 0.030541
0.79618 0.13655 0.77905 0.69875
0.88517 0.33536 0.65376 0.89092
0.91329 0.67973 0.49417 0.33416
0.098712 0.72123 0.71504 0.19781
Your help is highly appreciated! Thank you.
2 Comments
BN
on 28 Jul 2020
I think it could be done if you convert your table to matrix then sort it as you like and the return it to table. Jus an idea...
Accepted Answer
Harsha Priya Daggubati
on 30 Jul 2020
Hi,
As you can see from the data, whenever you apply sortrows to your table, by giving your column name as 'v' data will be sorted based on the first column of your merged column 'v'.
As a workaround, you can use 'splitvars' method to update your table and apply sortrows, then later merge your table which you need as a final result using 'mergevars'.
Here is the code to it:
a = [0.88517 ;0.91329;0.79618;0.098712;0.26187];
v = [ 0.33536 0.65376 0.89092; 0.67973 0.49417 0.33416; 0.13655 0.77905 0.69875; 0.72123 0.71504 0.19781; 0.10676 0.90372 0.030541];
tbl = table(a,v)
tbl1 = splitvars(tbl);
tbl1 = sortrows(tbl1,[4]);
finaltbl = mergevars(tbl1,[2 3 4],'NewVariableName','v');
Hope this helps!
0 Comments
More Answers (1)
Eric Sofen
on 12 Mar 2024
There isn't a one-line solution to this, but here's another approach that hoists the data you want to sort by out of the table and then uses the sort index (second output of sortrows) to sort the table itself:
% Setup
t = readtable("patients.xls",TextType="string");
t.BloodPressure = [t.Systolic, t.Diastolic];
t = removevars(t,["Systolic","Diastolic"]);
% Sort the second column of the BloodPressure Variable to get the sort order
[~,i] = sortrows(t.BloodPressure(:,2));
% Index back into t with the sort order.
tsorted = t(i,:)
0 Comments
See Also
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!