How to sortrows by specific strings
47 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
David Rodriguez
el 9 de Mzo. de 2021
Editada: David Rodriguez
el 14 de En. de 2023
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 comentarios
Respuesta aceptada
Steven Lord
el 10 de Mzo. de 2021
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 comentarios
Más respuestas (1)
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!