【问题标题】:Sort the fields in a struct based on value根据值对结构中的字段进行排序
【发布时间】:2020-04-10 01:24:15
【问题描述】:

假设我有一个结构:

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

我可以修改它,以便根据它们的值对字段进行排序:

MyStruct
c: 32
b: 22
a: 12

orderfields 方法允许基于字段名称或其他结构/单元格数组对结构进行排序,但不能按值排序。

【问题讨论】:

    标签: matlab sorting struct


    【解决方案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】:

      orderfieldsa syntax,它根据排列数组进行排序。 second output of sort 是一个排列数组。像这样的东西应该可以工作:

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

      【讨论】:

      • 是否根据字段名称排序?我需要基于价值观的订单。但我看到了大致的想法,@RM25483 的答案是相似的,并获得了正确的排列数组以根据值进行排序。
      • @Mansoor:你是对的,已修复(使用与其他答案不同的语法)。
      猜你喜欢
      • 1970-01-01
      • 2021-05-16
      • 2016-08-25
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 2011-08-13
      相关资源
      最近更新 更多