Reputation: 698
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!
Upvotes: 2
Views: 1415
Reputation: 11168
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.
Upvotes: 2