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!