【问题标题】:Sorting array of objects by property in MATLAB? [duplicate]在MATLAB中按属性对对象数组进行排序? [复制]
【发布时间】:2023-03-13 02:33:01
【问题描述】:

我有一个对象数组,每个对象都有不同的属性,我想弄清楚如何在数组上运行“排序”,指定每个对象的特定属性进行排序。

例如,假设我的对象是“椅子”,我想按 numlegs(腿数)的属性进行排序,那么我将能够对椅子数组运行排序函数,然后对它们进行排序通过他们拥有的腿数,例如“sort(chairs,numlegs)”。有没有办法做到这一点?

谢谢!

【问题讨论】:

    标签: arrays matlab sorting object


    【解决方案1】:

    排序对象数组

    • 定义一个类

    _

    classdef SimpleClass
        properties
            id
            numlegs
        end
        methods
            function obj = SimpleClass(id,numlegs)
                if nargin > 0
                    obj.id = id;
                    obj.numlegs = numlegs;
                end
            end
        end
    end
    
    • 排序

    _

    chairs = SimpleClass.empty(20,0);
    for ii = 1:20
        chairs(ii) = SimpleClass(ii, randi(4,1));
    end
    [~, ind] = sort([chairs.numlegs]);
    chairs_sorted = chairs(ind);
    

    输出

    _

    >> [chairs_sorted.numlegs]
    
    ans =
    
      Columns 1 through 10
    
         1     1     1     1     1     1     1     1     2     3
    
      Columns 11 through 20
    
         3     3     3     3     3     3     3     4     4     4
    
    >> [chairs_sorted.id]
    
    ans =
    
      Columns 1 through 10
    
         3     5     8     9    10    11    17    19    12     1
    
      Columns 11 through 20
    
         2     4     6     7    14    15    20    13    16    18
    

    排序结构数组

    chairs = struct('id',num2cell(1:20), 'numlegs',num2cell(randi(4, 1, 20)));
    [~, ind] = sort([chairs.numlegs]);
    chairs_sorted = chairs(ind);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 2011-09-06
      相关资源
      最近更新 更多