我有一个对象数组,每个对象都有各种属性,我想弄清楚如何在数组上运行“排序”,并指定要排序的每个对象的特定属性。
例如,假设我的对象是“椅子”,并且我想按numlegs(腿数)的属性进行排序,那么我将能够对一组椅子运行排序功能,并按数字对它们进行排序他们的腿像“排序(椅子,小腿)”。有什么办法吗?
谢谢!
定义一个类
_
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);