Code covered by the BSD License  

Highlights from
Nested sort of structure arrays

Be the first to rate this file! 26 Downloads (last 30 days) File Size: 6.48 KB File ID: #28573

Nested sort of structure arrays

by Jake Hughey

 

27 Aug 2010 (Updated 17 Sep 2010)

Perform a nested sort of a struct array based on multiple fields.

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information
Description

nestedSortStruct and nestedSortStruct2 do a nested sort of a one-dimensional struct array by two different methods. That is, the struct array is sorted by one field, then those entries of the array that have the same value for that field are sorted by a second field, etc.

If you want to sort by only one field, you can call nestedSortStruct and use a simple string instead of a cell array for fieldNamesCell, or you can simply call sortStruct.

The restrictions are that the fields must be single numbers or logicals, or chars (usually simple strings).

By default the struct array will be sorted in ascending order, but the functions include an option to sort in descending order.

nestedSortStruct will usually be faster than nestedSortStruct2. For nestedSortStruct, the speed of sorting is mostly independent of the order of the fieldnames in fieldNamesCell.

For nestedSortStruct2, the order of the fields in fieldNamesCell affects the speed. The sooner a field for which most entries in the struct array have unique values will be used to sort the struct array (i.e., the earlier its location in fieldNamesCell), the faster nestedSortStruct2 will be. If a field with mostly unique entries is the first field by which the struct array will be sorted, nestedSortStruct2 could be faster than nestedSortStruct.

nestedSortStruct could call sortStruct, and nestedSortStruct2 does call sortStruct2.

MATLAB release MATLAB 7.7 (R2008b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Please login to add a comment or rating.
Updates
31 Aug 2010

Minor fix to formatting of initial comments in nestedSortStruct2.m.

16 Sep 2010

Fixed nestedSortStruct so column struct arrays are sorted properly.

17 Sep 2010

Simplified nestedSortStruct to avoid converting from cell to matrix, resulting in ~20% speedup. Thanks Jori. Fixed minor naming inconsistencies in nestedSortStruct2.

Tag Activity for this File
Tag Applied By Date/Time
nested Jake Hughey 30 Aug 2010 12:00:45
sort Jake Hughey 30 Aug 2010 12:00:45
struct Jake Hughey 30 Aug 2010 12:00:45
array Jake Hughey 30 Aug 2010 12:00:45
sortrows Jake Hughey 30 Aug 2010 12:00:45
potw Shari Freedman 17 Sep 2010 10:00:51
array Jonathan Karr 09 Oct 2010 13:04:29
pick of the week Jiro Doke 11 Feb 2011 20:05:39
struct Jerry 10 Mar 2011 11:18:43

Contact us at files@mathworks.com