How to sortrows by specific strings
45 次查看(过去 30 天)
显示 更早的评论
I am making, an attendance sheet for a college club meeting. I have a table filled with names (string) and would like to sort them by their position (string).
I want to sort the list of people who sign in at the end of the meeting by their held "position."
1. Officers would appear at the top of the list
2. Members next
3. Guests last
However I am struggling to use sort or sortrows to do this, so there must be other commands that I could try. I provided example code and a desired output to better illustrate my question.
For example
% Create Data
Position = {'Vice President';'Guest';'Member';'President'};
Name = {'John';'Jane';'Nancy';'Bob'};
% Turn data into a table
data = table(Position,Name);
% Sort names by position:
% President->VP->Member->Guest
%%%% Your Helpful Advice would go here :) %%%%
Desired Output
%{
data =
4×2 table
Position Name
__________________ _________
{'President' } {'John' }
{'Vice President'} {'Jane' }
{'Member' } {'Nancy'}
{'Guest' } {'Bob' }
%}
Any suggestions are appreciated, thank you!
Updated to make question easier to understand for others.
0 个评论
采纳的回答
Steven Lord
2021-3-10
desired_order = {'President','Vice President','Member','Guest'};
Position = {'Vice President';'Guest';'Member';'President'};
Name = {'John';'Jane';'Nancy';'Bob'};
Turn the Position variable into a categorical array whose order matters (the array is an ordinal array.) The ordering is given by the desired_order list.
ranks = categorical(Position, desired_order, 'ordinal', true)
Store the data in a table array.
results = table(ranks, Name, 'VariableNames', ["Rank", "Name"])
Sort the table by Rank (taking advantage of the fact that it is ordinal.)
results = sortrows(results, "Rank")
Who's the Member?
results{results.Rank == 'Member', 'Name'}
2 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!