Sort the fields in a struct based on value

后端 未结 2 1628
悲&欢浪女
悲&欢浪女 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:32

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

提交回复
热议问题