【问题标题】:In Matlab, how can I sort the order of a nested structure?在 Matlab 中,如何对嵌套结构的顺序进行排序?
【发布时间】:2013-06-20 04:27:58
【问题描述】:

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

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;

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

【问题讨论】:

  • struct 的每个元素中的所有otherStruct 是否具有相同的calssAve 值?
  • 我首先建议不要对这样一个简单的数据进行这样的数据组织。
  • Shai,是的,struct 的每个元素中的所有 otherStruct 总是具有相同的 classAve 值。
  • Oleg,我正在处理的数据实际上非常大/复杂。如果我不使用嵌套结构,那么数据的组织将过于混乱。此外,我以最简单的形式展示了代码,这样我的问题就不会令人困惑。

标签: matlab sorting nested structure


【解决方案1】:

首先我建议使用另一个变量名(例如structA)而不是struct,因为那是function to create structs

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

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

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

【讨论】:

  • 另外也可以使用classAve = [StructA(:).classAve];
  • @HughNolan 不,你不能,因为还有另一个中间结构。而像structA(:).otherStruct(1).classAve 这样的东西显然不起作用,因为不能保证所有otherstructs 都具有相同的内容,这是在结构上使用标量索引所必需的。
  • 抱歉,我没有看到还有一层。理论上你可以做 Layer1= [StructA(:).otherStruct]; classAve = [Layer1(:).classAve] (如果他们有不同数量的字段会出错)但这有点傻,特别是如果你有更多的层要下去。
  • 感谢您的建议和解决方案。这非常有效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
  • 2019-12-27
  • 1970-01-01
相关资源
最近更新 更多