## Natural-Order Row Sort

version 3.3.0 (16 KB) by
Alphanumeric row sort of a cell/string/categorical array, with customizable numeric format.

Updated 14 Jul 2021

Editor's Note: This file was selected as MATLAB Central Pick of the Week

To sort any file-names or folder-names use NATSORTFILES:
To sort the elements of a string/cell array use NATSORT:
### Summary ###
Alphanumeric sort the rows of a string/cell/categorical array. Similar to MATLAB's SORTROWS function, but takes into account the values of any numeric substrings. Compare for example:
>> X = {'x2','10';'x10','0';'x1','0';'x2','2'};
>> sortrows(X) % Wrong numeric order
ans =
'x1' '0'
'x10' '0'
'x2' '10'
'x2' '2'
>> natsortrows(X) % Correct numeric order
ans =
'x1' '0'
'x2' '2'
'x2' '10'
'x10' '0'
By default NATSORTROWS interprets all consecutive digits as integer numbers, the number substring recognition can be specified using a regular expression: see NATSORT for details.
### File Dependency ###
The natural-order sort is provided by the function NATSORT (File Exchange 34464). All of NATSORT's optional inputs are supported by NATSORTROWS.
### Examples ###
>> A = {'B','2','X';'A','100','X';'B','10','X';'A','2','Y';'A','20','X'};
>> sortrows(A) % wrong number order:
ans =
'A' '100' 'X'
'A' '2' 'Y'
'A' '20' 'X'
'B' '10' 'X'
'B' '2' 'X'
>> natsortrows(A)
ans =
'A' '2' 'Y'
'A' '20' 'X'
'A' '100' 'X'
'B' '2' 'X'
'B' '10' 'X'
>> natsortrows(A,[],'descend')
ans =
'B' '10' 'X'
'B' '2' 'X'
'A' '100' 'X'
'A' '20' 'X'
'A' '2' 'Y'
>> sortrows(A,[2,-3]) % Wrong number order:
ans =
'B' '10' 'X'
'A' '100' 'X'
'A' '2' 'Y'
'B' '2' 'X'
'A' '20' 'X'
>> natsortrows(A,[],[2,-3])
ans =
'A' '2' 'Y'
'B' '2' 'X'
'B' '10' 'X'
'A' '20' 'X'
'A' '100' 'X'
>> B = {'ABCD';'3e45';'67.8';'+Inf';'-12';'+9';'NaN'};
>> sortrows(B) % wrong number order:
ans =
'+9'
'+Inf'
'-12'
'3e45'
'67.8'
'ABCD'
'NaN'
>> natsortrows(B,'[-+]?(NaN|Inf|\d+\.?\d*(E[-+]?\d+)?)')
ans =
'-12'
'+9'
'67.8'
'3e45'
'+Inf'
'NaN'
'ABCD'

### Cite As

Stephen (2021). Natural-Order Row Sort (https://www.mathworks.com/matlabcentral/fileexchange/47433-natural-order-row-sort), MATLAB Central File Exchange. Retrieved .

##### MATLAB Release Compatibility
Created with R2010b
Compatible with any release
##### Platform Compatibility
Windows macOS Linux

### Community Treasure Hunt

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

Start Hunting!