MATLAB: Do the DIR and LS functions in MATLAB not sort numerical filenames in numerical order

alphabeticalphabeticalarrangedatadelimiteddelimiterdirdirectoryfilefilenamefilesimageslsMATLABnatsortfilesnumericnumericalorderreadrearrangeresortroutinesortsortingwindows

The DIR and LS functions in MATLAB do not sort numerical filenames in numerical order.
For example, I have filenames of the form:
1-1-1.tif
1-1-2.tif
1-1-3.tif
. . .
1-1-9.tif
1-1-10.tif
1-1-11.tif
However, when I use DIR or LS to list the files using:
files=dir('*.tif')
The results stored in "dir.name" are:
1-1-1.tif
1-1-10.tif
1-1-11.tif
1-1-2.tif
1-1-3.tif
1-1-9.tif
I would like to order these numerically.

Best Answer

The DIR or LS functions in MATLAB sort the strings in ASCII dictionary order. This can cause a problem if you want to sort numbered files which do not have leading zeros.
Currently, to work around this problem, you can use the text manipulation and sorting routines in MATLAB.
Here is an example:
files=dir('*.tif');
numfiles = size(files,1); % Find number of files
numdelim = 3; % Number of delimiters
delims = ['-' '.']; % Delimiters used
% Create a matrix of the file list index and the delimiters
filenums=[ [1:numfiles]' zeros(numfiles,3) ];
for i=1:numfiles % Cycles through list of files
rem=files(i).name;
for j=1:numdelim % Cycles through the filename delimiters
[token,rem] = strtok(rem,delims);
filenums(i,j+1) = str2num(token);
end
end
% Sort the matrix by rows
filenums = sortrows(filenums,[2:numdelim+1]);
% Show the filenames in the new order
files(filenums(:,1)).name
% Create a cell array of the filenames in new order
for i=1:numfiles
sortedfiles{i,1} = files(filenums(i,1)).name;
end
Related Question