In Matlab, how can I sort the order of a nested structure?

橙三吉。 提交于 2019-12-24 00:35:02

问题


I am trying to sort the order of a nested structure in descending order by a specified parameter. Please refer to the following nested structure:

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;

My goal is to sort the structure above by the highest classAve to the lowest. I would like to sort by the parent structure "struct". As an illustration of what I would like the output to be, please refer to the code below. Notice that the nested structure is now in descending order by classAve but reassigned within the parent structure.

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;

If anyone has suggestions on an easy way to accomplish this, any help would be greatly appreciated. Thank you!


回答1:


Firstly I'd suggest using another variable name (eg structA) instead of struct since that's a function to create structs.

Then to solve your problem (assuming each otherStruct child has the same classAve):

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

The first line is the largest hurdle to jump; it extracts the indices of the first otherStruct in each array element of the big struct. The following two lines are trivial for sorting stuff.



来源:https://stackoverflow.com/questions/17205277/in-matlab-how-can-i-sort-the-order-of-a-nested-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!