【发布时间】:2023-03-13 02:33:01
【问题描述】:
我有一个对象数组,每个对象都有不同的属性,我想弄清楚如何在数组上运行“排序”,指定每个对象的特定属性进行排序。
例如,假设我的对象是“椅子”,我想按 numlegs(腿数)的属性进行排序,那么我将能够对椅子数组运行排序函数,然后对它们进行排序通过他们拥有的腿数,例如“sort(chairs,numlegs)”。有没有办法做到这一点?
谢谢!
【问题讨论】:
标签: arrays matlab sorting object
我有一个对象数组,每个对象都有不同的属性,我想弄清楚如何在数组上运行“排序”,指定每个对象的特定属性进行排序。
例如,假设我的对象是“椅子”,我想按 numlegs(腿数)的属性进行排序,那么我将能够对椅子数组运行排序函数,然后对它们进行排序通过他们拥有的腿数,例如“sort(chairs,numlegs)”。有没有办法做到这一点?
谢谢!
【问题讨论】:
标签: arrays matlab sorting object
_
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);
【讨论】: