Why do the DIR and LS functions in MATLAB not sort numerical filenames in numerical order?
27 次查看(过去 30 天)
显示 更早的评论
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.
采纳的回答
MathWorks Support Team
2009-6-27
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
4 个评论
Stephen23
2021-5-17
编辑:Stephen23
2021-8-16
"The DIR or LS functions in MATLAB sort the strings in ASCII dictionary order."
Easily disproved by actually running LS and DIR on a few very basic filenames:
ls *.txt
dir *.txt
Note that those are different orders.
Different orders means it is not possible for both of them to be "in ASCII dictionary order" as this answer (most likely incorrectly) states that MATLAB sorts them into. One of them does happen to be in ASCII order, but certainly not both of them (unless MST has invented a completely new, undocumented, variable ASCII order).
Walter Roberson
2021-8-13
The R2021a documentation for dir() and ls() do not document any ordering.
ASCII dictionary order is not likely, as the supported operating systems use various forms of unicode.
I just did a test on my Mac;
!touch q R
ls
On my Mac, R was before q -- which is consistent with sorting by codepoint, but is not consistent with ascii dictionary order.
更多回答(1 个)
Stephen23
2017-1-29
编辑:Stephen23
2021-4-18
Simple solution: download my FEX submission natsortfiles, which sorts filenames into alphanumeric order:
S = dir('*.txt');
S.name
S = natsortfiles(S); % alphanumeric sort by filename
S.name
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!