MATLAB - 按子结构字段对结构进行排序
MATLAB - Sort struct by substruct field
我是 Matlab 的新用户,我对结构有一些疑问。
我的情况是:
我有一个结构 P1,它有 3 个 "substructs"(A1、A2、A3)和两个字段(姓名和年龄),我想按年龄对我的 "substructs" 进行排序。所以,我有它:
P1.A1.age = 33
P1.A2.age = 23
P1.A3.age = 31
我想要这个结果:
P1.A2.age = 23
P1.A3.age = 31
P1.A1.age = 33
有什么想法吗?
我尝试使用函数 orderfields,但没有得到我想要的结果。
谢谢!!!
这对你有用吗?
>> [val idx]=sort(arrayfun(@(x) P1.(sprintf('A%d',x)).age,1:3))
val =
23 31 33
idx =
2 3 1
首先使用 sort
和 structfun
获得排序所需的排列。然后使用 orderfields
:
应用该排列
[~, I] = sort(structfun(@(x) x.age, P1));
P1 = orderfields(P1, I);
我是 Matlab 的新用户,我对结构有一些疑问。
我的情况是:
我有一个结构 P1,它有 3 个 "substructs"(A1、A2、A3)和两个字段(姓名和年龄),我想按年龄对我的 "substructs" 进行排序。所以,我有它:
P1.A1.age = 33
P1.A2.age = 23
P1.A3.age = 31
我想要这个结果:
P1.A2.age = 23
P1.A3.age = 31
P1.A1.age = 33
有什么想法吗?
我尝试使用函数 orderfields,但没有得到我想要的结果。
谢谢!!!
这对你有用吗?
>> [val idx]=sort(arrayfun(@(x) P1.(sprintf('A%d',x)).age,1:3))
val =
23 31 33
idx =
2 3 1
首先使用 sort
和 structfun
获得排序所需的排列。然后使用 orderfields
:
[~, I] = sort(structfun(@(x) x.age, P1));
P1 = orderfields(P1, I);