Sorting an array of strings based on number pattern

65 ビュー (過去 30 日間)
Niels
Niels 2015 年 7 月 14 日
コメント済み: Ali M 2024 年 6 月 19 日
I'm looking for an efficient way to solve the following issue:
Typically I read out all files in a directory that match a certain pattern by means of the dir function:
dirFiles = dir('Common_*_common.ext');
fileNames= {dirFiles.name};
This does what it is supposed to do and gives me a nice cell array with files I need to load.
However, the pattern is of the format 0, 1, 2, ..., 8, 9, 10 and the order of my fileNames comes out as 0, 10, 1, ..., 7, 8, 9. Unfortunately, changing the filenames themselves to 00, 01, 02, ..., 10 is not an option. Is there an efficient way to sort such arrays to the correct format?
Of course this should also hold when the sequence increases to larger numbers (e.g. 0, 1, 2, ..., 29, 30, 31).
  1 件のコメント
Stephen23
Stephen23 2016 年 2 月 22 日
編集済み: Stephen23 2021 年 4 月 18 日
You could download my FEX submission natsortfiles. The function natsortfiles does not perform a naive natural-order sort, but also sorts the filenames and file extensions separately so that the file extension period character does not influence the sort output.
>> 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'

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

採用された回答

Niels
Niels 2015 年 7 月 14 日
編集済み: Niels 2015 年 7 月 14 日
Ok, I should've searched better...
Problem solved with a PotW tool by Stephen Cobeldick.

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2015 年 7 月 14 日
Here is a way:
% create some example names
filenames = {'xx_1_yy.txt','xx_8_yy.txt','xx_10_yy.txt','xx_2_yy.txt'}
sort(filenames) % wrong!
% extract the numbers
filenum = cellfun(@(x)sscanf(x,'xx_%d_yy.txt'), filenames)
% sort them, and get the sorting order
[~,Sidx] = sort(filenum)
% use to this sorting order to sort the filenames
SortedFilenames = filenames(Sidx)
  3 件のコメント
Stephen23
Stephen23 2016 年 2 月 22 日
編集済み: Stephen23 2016 年 2 月 22 日
@Niels: this is a good solution, but it works only for this filename format: any change in filename format will mean that you need to change your code. For multiple numbers in one name, or sorting by characters and numeric values it gets quite complicated. That is why I wrote my FEX submission natsortfiles, which naturally deals with all of these situations. You can change the filename format and natsortfiles will still work.
Ali M
Ali M 2024 年 6 月 19 日
Thanks Jos, this was a genius peace of code thank you!

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by