Sort the fields in a struct based on value

后端 未结 2 1630
悲&欢浪女
悲&欢浪女 2021-01-24 20:17

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:

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-24 20:46

    % 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 )
    

提交回复
热议问题