在MATLAB中按属性对对象数组进行排序?

3
我有一个对象数组,每个对象都有不同的属性,我想找出如何在数组上运行“sort”,指定要按其排序的每个对象的特定属性。
例如,假设我的对象是“椅子”,我想按numlegs(腿的数量)属性排序,那么我就可以在椅子数组上运行一个sort函数,并且它会像“sort(chairs,numlegs)”一样按它们拥有的腿数进行排序。有没有办法这样做?
谢谢!
1个回答

9

对对象数组进行排序

  • 定义一个类

_

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接