Put in alphabet order a structure only by one field

Hi, i have a struct called "users" that contains fields such as "name","username","password".I want do display all the structure's data but it has to be alphabettically organized by name. How can i do this using sort?

댓글 수: 1

Stephen23
Stephen23 2017년 12월 18일
편집: Stephen23 2017년 12월 18일
@José Pereira: which of these do you have:
  1. a non-scalar structure with scalar fields (or char vectors), or
  2. a scalar structure with non-scalar fields?

댓글을 달려면 로그인하십시오.

답변 (2개)

Walter Roberson
Walter Roberson 2017년 12월 18일
[~, sortidx] = sort({users.name});
users = users(sortidx);

댓글 수: 3

+1 No need at all for conversions to tables etc...
Assumes a non-scalar structure... which the question does not specify.
True. If it is a scalar structure with cell arrays of character vectors, and will all fields having the same number of entries (but fields possibly being different data types from each other)
[~, sortidx] = sort(users.name);
users = structfun(@(F) F(sortidx), users, 'uniform', 0);

댓글을 달려면 로그인하십시오.

Harish Ramachandran
Harish Ramachandran 2017년 12월 18일
편집: Harish Ramachandran 2017년 12월 18일
Hello,
Unfortunately, there is no direct way to sort a structure according to one of the field. The steps below involve transforming the structure into a table, perform the ' sortrows' operation and reverting back to a structure. I have also attached a couple of relevant links which you can check out.
  • Create a predefined structure - users
users = struct('name', {'Noah', 'Liam', 'Mason', 'Jacob', 'William', 'Ethan', 'James', 'Alexander'},...
'username', {'NH', 'LM', 'MN', 'JB', 'WM', 'EN', 'JS', 'AR'},...
'password', {'NH147', 'LM258', 'MN@234', 'JB369', 'WM1991', 'EN4567', 'JS#345', 'AR/*-789'})
  • Convert the structure into a table.
user_Table = struct2table(users);
  • You can view the contents of the table using the ' disp' function:
disp(user_Table)
  • Sort the table with the key being the 'name' column.
user_Table = sortrows(user_Table,'name');
  • Revert back to a structure
users = table2struct(user_Table);
You can also check out the links below:
  1. sortrows - Sort rows of matrix or table
  2. Advantages of using Tables
  3. Related question in MATLAB Answers repository
  4. File Exchange Blog - Sorting Structure Arrays based on Fields
  5. Printing the contents of a structure onto the command window

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

질문:

2017년 12월 7일

댓글:

2017년 12월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by