To sort the elements of a string/cell array use
NATSORT
:
To sort the rows of a string/cell array use
NATSORTROWS
:
Summary
Alphanumeric sort the text in a string/cell/structure array. Sorts the text by character code taking into account the values of any number substrings. Compare for example:
>> A = {'a2.txt','a10.txt',“a1.txt”};
>> sort(A)
ans =“a1.txt”'a10.txt''a2.txt'
>> natsortfiles(A)
ans =“a1.txt”'a2.txt''a10.txt'
By default
NATSORTFILES
interprets all consecutive digits as integer numbers, the number substring recognition can be specified using a regular expression: see
NATSORT
for details.
NATSORTFILES
does not perform a naive natural-order sort, but sorts the filenames and file extensions separately to ensure a dictionary sort, where shorter filenames always sort before longer ones. Likewise filepaths are split at each file-separator character, and each level of the file hierarchy is sorted separately.
Example with DIR()
P ='C:\SomeDir\SubDir';
S = dir(fullfile(P,'*.txt'));
S = natsortfiles(S);
fork = 1:numel(S)
F = fullfile(P,S(k).name)
end
File Dependency
The natural-order sort is provided by the function
NATSORT
(File Exchange 34464). All of
NATSORT
's optional inputs are supported by
NATSORTFILES
.
Examples
>> A = {'a2.txt','a10.txt',“a1.txt”}
>> sort(A)
ans =“a1.txt”'a10.txt''a2.txt'
>> natsortfiles(A)
ans =“a1.txt”'a2.txt''a10.txt'
>> B = {'test2.m';'test10-old.m';'test.m';'test10.m';'test1.m'};
>> sort(B)
ans =
'test.m'
'test1.m'
'test10-old.m'
'test10.m'
'test2.m'
>> natsortfiles(B)
ans =
'test.m'
'test1.m'
'test2.m'
'test10.m'
'test10-old.m'
>> C = {'A2-old\test.m';'A10\test.m';'A2\test.m';'A1\test.m';'A1-archive.zip'};
>> sort(C)
ans =
'A1-archive.zip'
'A10\test.m'
'A1\test.m'
'A2-old\test.m'
'A2\test.m'
>> natsortfiles(C)
ans =
'A1\test.m'
'A1-archive.zip'
'A2\test.m'
'A2-old\test.m'
'A10\test.m'
>> D = {'A1\B','A+/B','A/B1','A=/B','A\B0'};
>> sort(D)
ans ='A+/B''A/B1''A1\B''A=/B''A\B0'
>> natsortfiles(D)
ans ='A\B0''A/B1''A1\B''A+/B''A=/B'
>> F = {'test_new.m';'test-old.m';'test.m'};
>> sort(F)
ans =
'test-old.m'
'test.m'
'test_new.m'
>> natsortfiles(F)
ans =
'test.m'
'test-old.m'
'test_new.m'