How do I sort filenames containing text and numbers in numerical order in MATLAB?

266 ビュー (過去 30 日間)
I have a series of .png files in a folder whose names are the following;
In reading the MATLAB documentation, I understand the dir function sorts strings in ASCII dictionary order. And since the files I'm using have no leading zeros, this is a problem. This is exactly what I'm seeing when I use the dir function:
A = dir('*.png');
But what I need is this;
A = dir('*.png');
I know this can be done if the filenames contain only numbers.
But is it possible to sort these filenames (in numerical order) using existing text manipulation and sorting routines in MATLAB? If so, how?
  2 件のコメント
Msutto51 2020 年 2 月 6 日
編集済み: Stephen23 2020 年 12 月 18 日
Natsortfiles works perfectly!!! thanks !



Cedric Wannaz
Cedric Wannaz 2017 年 10 月 10 日
編集済み: Cedric Wannaz 2017 年 10 月 10 日
If, for any reason, you cannot install this function, you can sort your filenames as follows:
[~, reindex] = sort( str2double( regexp( {}, '\d+', 'match', 'once' )))
A = A(reindex) ;
Note that it assumes that all files have the same base name. If you have to deal with various base names, then you need the function mentioned in the other answers, or to work a little more on the sorting.
  5 件のコメント
Stephen23 2018 年 9 月 21 日
編集済み: Stephen23 2021 年 4 月 18 日
"You'll have to write a custom parsing routine to extract out the numbers you want into numerical vectors then sort them yourself."
You don't have to do that at all: natsortfiles handles multiple number values already. Just provide an appropriate regular expression, and it will work just fine:
>> C = {...
>> natsortfiles(C,'\d+\.?\d*') % alphanumeric sort
ans =


その他の回答 (2 件)

KSSV 2017 年 10 月 10 日
  2 件のコメント
Jan 2017 年 10 月 10 日
Really? But it is on the same server as the forum. Perhaps it works if you insert your country code:


Image Analyst
Image Analyst 2017 年 10 月 10 日


Find more on Large Files and Big Data in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by