2

我正在尝试按指定参数按降序对嵌套结构的顺序进行排序。请参考以下嵌套结构:

struct(1).otherStruct(1).name = 'A';
struct(1).otherStruct(1).classAve = 21;
struct(1).otherStruct(2).name = 'B';
struct(1).otherStruct(2).classAve = 21;
struct(1).otherStruct(3).name = 'C';
struct(1).otherStruct(3).classAve = 21;

struct(2).otherStruct(1).name = 'D';
struct(2).otherStruct(1).classAve = 13;
struct(2).otherStruct(2).name = 'E';
struct(2).otherStruct(2).classAve = 13;
struct(2).otherStruct(3).name = 'F';
struct(2).otherStruct(3).classAve = 13;

struct(3).otherStruct(1).name = 'G';
struct(3).otherStruct(1).classAve = 24;
struct(3).otherStruct(2).name = 'H';
struct(3).otherStruct(2).classAve = 24;
struct(3).otherStruct(3).name = 'I';
struct(3).otherStruct(3).classAve = 24;

我的目标是将上面的结构按最高的 classAve 排序到最低。我想按父结构“struct”排序。作为我希望输出的说明,请参阅下面的代码。请注意,嵌套结构现在按 classAve 降序排列,但在父结构中重新分配。

struct(1).otherStruct(1).name = 'G';
struct(1).otherStruct(1).classAve = 24;
struct(1).otherStruct(2).name = 'H';
struct(1).otherStruct(2).classAve = 24;
struct(1).otherStruct(3).name = 'I';
struct(1).otherStruct(3).classAve = 24;

struct(2).otherStruct(1).name = 'A';
struct(2).otherStruct(1).classAve = 21;
struct(2).otherStruct(2).name = 'B';
struct(2).otherStruct(2).classAve = 21;
struct(2).otherStruct(3).name = 'C';
struct(2).otherStruct(3).classAve = 21;

struct(3).otherStruct(1).name = 'D';
struct(3).otherStruct(1).classAve = 13;
struct(3).otherStruct(2).name = 'E';
struct(3).otherStruct(2).classAve = 13;
struct(3).otherStruct(3).name = 'F';
struct(3).otherStruct(3).classAve = 13;

如果有人对完成此操作的简单方法有建议,我们将不胜感激。谢谢!

4

1 回答 1

2

首先,我建议使用另一个变量名(例如structA)而不是struct因为这是一个创建 structs 的函数

然后解决你的问题(假设每个otherStruct孩子都有相同的classAve):

classAve = arrayfun(@(ii) structA(ii).otherStruct(1).classAve,1:numel(structA));
[~, sort_idx] = sort(classAve,'descend');
structAsorted = structA(sort_idx);

第一行是最大的障碍;它提取otherStruct大结构的每个数组元素中第一个的索引。以下两行对于排序内容是微不足道的。

于 2013-06-20T07:19:39.610 回答