Sorting Nested Structures based on Name
이전 댓글 표시
Hi all,
I have a code that imports folders full of data files and organizes/processes them based on file type. As it currently works, the data gets organized into a struct that has multiple sub-structs containing measurement data. I need the rows of data sorted by name but have not found a way to get the sub-structs sorted as well.
Currently, the data looks like this when imported:


I'd like to reorder the data so that the rows are sorted by name, but I can only get the main struct sorted this way, not the sub-structs as well. I'm using R2018b if that helps.
채택된 답변
추가 답변 (1개)
Bryant Lash
2021년 10월 21일
You should be able to perform the same code you do on the top level to any beneath it using a for loop.
If you need a solution where you can't assume the search depth, it will be more complex and require recusion.
Example code:
mainStruct = orderfields(mainStruct);
fields = fieldnamse(mainStruct);
for i = 1:size(fields,1)
mainStruct.(fields{i}) = orderfields(mainStruct.(fields{i}));
end
댓글 수: 5
Bryant Lash
2021년 10월 21일
So I'm not clear what you're looking for. My understanding is you have a top-level structure with N fields, then need to sort those struct fields based on the order of their names.
(I'll ignore the fact that the field names you listed aren't valid field names given the start with a number :) )
Instead, you want to reorder which rows?
"I needed to re-order the rows to be in numerical order,"
What rows?
The only thing in your screenshots that have more than one row are the tables:
- RATESHAPE structure has size 1x10 (i.e. only one row).
- the field NAME is in all elements a 1xN character vector (i.e. only one row each).
- the field DATA is in all elements a 1xN structure (i.e. only one row each).
- the field DATA.NAME is in all elements a 1xN character vector (i.e. only one row each).
- the field DATA.RATESHAPES is in elements a 256x3 table (i.e. 256 rows).
The tables are the only things with non-trivial numbers of rows. So you really want to sort the tables?
Smith
2021년 10월 21일
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!