How to sort a structure array based on a specific field

조회 수: 82 (최근 30일)
MathWorks Support Team
MathWorks Support Team 2018년 4월 17일
편집: Bruno Luong 2020년 8월 3일
How do we sort a structure array based on a specific field?

채택된 답변

MathWorks Support Team
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

추가 답변 (1개)

Norbert Nitzsche
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
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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

제품


릴리스

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by