How to sort a structure array based on a specific field

146 ビュー (過去 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 Center および File ExchangeStructures についてさらに検索

タグ

タグが未入力です。

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by