- a non-scalar structure with scalar fields (or char vectors), or
- a scalar structure with non-scalar fields?
Put in alphabet order a structure only by one field
20 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Walter Roberson
2017-12-18
[~, sortidx] = sort({users.name});
users = users(sortidx);
3 个评论
Walter Roberson
2017-12-18
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
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:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!