The problem about dir function

7 ビュー (過去 30 日間)
petter
petter 2012 年 3 月 28 日
編集済み: Stephen23 2021 年 4 月 18 日
hi every one:
when I use dir function to get the same type files of a file, (the file name is 10.png, 20.png, 50.png, 100.png, 200.png, 300.png, 1000.png), then I find the sequence is 10.png, 100.png, 1000.png, 20.png, 200.png.....
but what I want to get is the sequence like 10.png, 20.png, 50.png, 100.png, 200.png, 300.png, 1000.png
so please give me some suggestion or any help
thanks a lot
  1 件のコメント
Stephen23
Stephen23 2015 年 5 月 27 日
編集済み: Stephen23 2021 年 4 月 18 日
A simple solution is to use my FEX submission natsortfiles
>> S = dir('*.txt');
>> S.name
ans =
'1.txt'
ans =
'10.txt'
ans =
'2.txt'
>> S = natsortfiles(S); % alphanumeric sort by filename
>> S.name
ans =
'1.txt'
ans =
'2.txt'
ans =
'10.txt'

サインインしてコメントする。

採用された回答

Jan
Jan 2012 年 3 月 28 日
The most practical method is to use "0010" instead of "10". Then the numerical order equals the lexicographical order.
While there are some FEX submissions for "natural sorting", you can sort the names manually also:
List = dir('*.png');
Name = {List.name};
S = sprintf('%s,', Name{:}); % '10.png,100.png,1000.png,20.png, ...'
D = sscanf(S, '%d.png,'); % [10; 100, 1000; 20; ...]
[sortedD, sortIndex] = sort(D); % Sort numerically
sortedName = Name(sortIndex); % Apply sorting index to original names
  1 件のコメント
petter
petter 2012 年 3 月 28 日
Thanks a lot
Indeed I use the practical method mentioned by you, and solve the problem
I can,t understand clearly the method that you introduce.

サインインしてコメントする。

その他の回答 (1 件)

David Young
David Young 2012 年 3 月 28 日
You could do something like this:
dstruct = dir('*.png');
names = {dstruct.name};
maxlen = max(cellfun(@length, names));
padname = @(s) sprintf(['%0' num2str(maxlen) 's'], s);
namesPadded = cellfun(padname, names, 'UniformOutput', false);
[~, sortOrder] = sort(namesPadded);
dstruct = dstruct(sortOrder);
The structure is now in the order you want. To see this, you can execute
disp({dstruct.name})
  1 件のコメント
petter
petter 2012 年 3 月 28 日
Thanks to David
your method is so clever,I like it.
And I use it to absolutely solve my problem.
Thanks again.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by