How to sort a structure array based on a specific field
조회 수: 82 (최근 30일)
이전 댓글 표시
How do we sort a structure array based on a specific field?
채택된 답변
MathWorks Support Team
2018년 4월 17일
We have an instruction blog on how to do that in older versions of MATLAB (before R2013b):
If you are using a MATLAB version newer than R2013b, you can take advantage of the "sortrows" function in tables for a simpler workflow:
>> % suppose 's' is the struct array. 'DOB' is the field that contains date and time.
>> T = struct2table(s); % convert the struct array to a table
>> sortedT = sortrows(T, 'DOB'); % sort the table by 'DOB'
>> sortedS = table2struct(sortedT) % change it back to struct array if necessary
댓글 수: 0
추가 답변 (1개)
Norbert Nitzsche
2019년 7월 25일
편집: Norbert Nitzsche
2019년 7월 25일
% suppose 's' is the struct array and you want to sort it by the values in field 'f_sortby'
[x,idx]=sort([s.f_sortby]);
s=s(idx);
댓글 수: 1
Bruno Luong
2020년 8월 3일
편집: Bruno Luong
2020년 8월 3일
"Using curly braces should work for both numerical and text values"
Not for me
>> s=struct('num', {1 2 3})
s =
1×3 struct array with fields:
num
>> s(1)
ans =
struct with fields:
num: 1
>> s(3)
ans =
struct with fields:
num: 3
>> [x,idx]=sort({s.num})
Error using sort
Input argument must be a cell array of character vectors.
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!