Sort the fields in a struct based on value

萝らか妹 提交于 2020-08-20 06:16:18

问题


Say I have a struct:

MyStruct.a = 12;
MyStruct.b = 22;
MyStruct.c = 32;

Can I modify it so that the fields are ordered based on their value:

MyStruct
c: 32
b: 22
a: 12

The orderfields methods allow ordering of the struct based on the field name or other structures/cell arrays, but not by value.


回答1:


% Define initial structure:

myStruct.a = 12;
myStruct.b = 22;
myStruct.c = 32;

% Find desired order of values, rather than fieldnames:

[ ~,sortIdx ] = sort( structfun( @(x) x, myStruct ), 'descend' );

% Apply orderfields():

mySortedStruct = orderfields( myStruct, sortIdx )



回答2:


orderfields has a syntax where it orders based on a permutation array. The second output of sort is a permutation array. Something like this should work:

[~,I] = sort(cell2mat(struct2cell(MyStruct)));
I = flip(I); % reverse ordering to get larger elements first
MyStruct = orderfields(MyStruct,I);


来源:https://stackoverflow.com/questions/59375970/sort-the-fields-in-a-struct-based-on-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!