How to sort a structure array based on a specific field

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 Comments

More Answers (1)

Norbert Nitzsche on 25 Jul 2019

Direct link to this answer

Cancel Copy to Clipboard

Direct link to this answer

Cancel Copy to Clipboard Edited: Norbert Nitzsche on 25 Jul 2019 % 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]);
1 Comment
Bruno Luong on 3 Aug 2020

Direct link to this comment

Cancel Copy to Clipboard

Direct link to this comment

Cancel Copy to Clipboard Edited: Bruno Luong on 3 Aug 2020 "Using curly braces should work for both numerical and text values" Not for me >> s=struct( 'num' , <1 2 3>) 1 × 3 struct array with fields: struct with fields: struct with fields: Error using sort Input argument must be a cell array of character vectors.

See Also

Categories

Find more on Structures in Help Center and File Exchange

Tags

No tags entered yet.

Products

Release

Community Treasure Hunt

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

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.